Suppose I have an interface and an implementation class that implements it, and I want to write unit-test for this. What should I check the interface or Impl?
Here is an example:
public interface HelloInterface { public void sayHello(); } public class HelloInterfaceImpl implements HelloInterface { private PrintStream target = System.out; @Override public void sayHello() { target.print("Hello World"); } public void setTarget(PrintStream target){ this.target = target; } }
So, I have HelloInterface and HelloInterfaceImpl that implements it. What is an incomplete testing interface or Impl?
I think it should be HelloInterface. Consider the following JUnit test sketch:
public class HelloInterfaceTest { private HelloInterface hi; @Before public void setUp() { hi = new HelloInterfaceImpl(); } @Test public void testDefaultBehaviourEndsNormally() { hi.sayHello();
The main line is the one I commented on.
((HelloInterfaceImpl)hi).setTarget(target);
The setTarget() method is not part of my public interface, so I donโt want to accidentally call it. If I really want to call it, I should think about it. This helps me, for example, to discover that I'm really trying to inject an addiction. This opens up for me the whole world of new opportunities. I can use some existing dependency injection mechanism (for example, Spring), I can imitate it myself, as it actually was in my code, or use a completely different approach. Take a closer look, preparing PrintSream is not so easy, maybe I should use a mock object instead?
EDIT : I think I should always focus on the interface. From my point of view, setTarget() not part of the โcontractโ of the impl class, and it serves to inject dependencies. I think that any public method of the Impl class should be considered private in terms of testing. This does not mean that I am ignoring implementation details.
See also. Should private / protected methods be under unit test?
EDIT-2 In the case of multiple implementations / multiple interfaces, I would test all implementations, but when I declare a variable in my setUp() method, I would definitely use the interface.
java dependency-injection unit-testing mockito
alexsmail Jun 07 '12 at 18:33 2012-06-07 18:33
source share