How can i test an interface?

前端 未结 4 470
刺人心
刺人心 2021-01-07 09:13

I want to do a JUnit test case for an interface, as you know i can\'t make an object from the interface and i don\'t want any classes names to show up in that test, i want o

相关标签:
4条回答
  • 2021-01-07 09:18

    There is no functionality to test in an interface (because it cannot be instantiated; it has no method implementations). So there is nothing JUnit can do with it.

    0 讨论(0)
  • 2021-01-07 09:25

    An interface is a contract. It has no logic to test.

    You can use a mocking framework like Mockito to create an instance of the interface without having to manually stub the methods. But it will just stub them in the background.

    You have to ask yourself what you want to test? Given that the interface methods have no implementation there is no code to test.

    Say I have an interface like so

    public interface DoesStuff {
        void doStuff();
    }
    

    What is there to test? The only thing I have said is that I want a class that implements DoesStuff to doStuff.

    0 讨论(0)
  • 2021-01-07 09:30

    You could make an abstract base class for unit tests. For specific classes that implement the interface a unit test would simply extend the abstract base class.

    The abstract base class could test things that should hold, like close after open or other things.

    0 讨论(0)
  • 2021-01-07 09:41

    The only way to test an interface is to create a concrete class that implements it, instantiate it and test that class. You can't test an interface directly, because as you know, it can't be instantiated, leaving nothing to be tested. This should be obvious: an interface is just a collection of method signatures, with no method bodies - hence there is no behavior to be tested.

    0 讨论(0)
提交回复
热议问题