假设我有实现它的接口和实现类,并且我想为此编写单元测试。我应该测试什么接口或Impl?
这是一个例子:
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;
}
}
因此,我有实现它的HelloInterface和HelloInterfaceImpl。什么是被测单元接口或Impl?
我认为应该是HelloInterface。请考虑以下JUnit测试草图:
public class HelloInterfaceTest {
private HelloInterface hi;
@Before
public void setUp() {
hi = new HelloInterfaceImpl();
}
@Test
public void testDefaultBehaviourEndsNormally() {
hi.sayHello();
// no NullPointerException here
}
@Test
public void testCheckHelloWorld() throws Exception {
ByteArrayOutputStream out = new ByteArrayOutputStream();
PrintStream target = new PrintStream(out);
PrivilegedAccessor.setValue(hi, "target", target);
//You can use ReflectionTestUtils in place of PrivilegedAccessor
//really it is DI
//((HelloInterfaceImpl)hi).setTarget(target);
hi.sayHello();
String result = out.toString();
assertEquals("Hello World", result);
}
}
主线实际上是我注释掉的那条线。
((HelloInterfaceImpl)hi).setTarget(target);
方法setTarget()不是我的公共接口的一部分,所以我不想 意外地
调用它。如果我真的想打电话给我,我应该花点时间考虑一下。例如,它可以帮助我发现我真正想做的是依赖注入。它为我打开了整个新机遇的世界。我可以使用一些现有的依赖注入机制(例如Spring的依赖注入机制),我可以像在代码中实际进行的那样自己模拟它,或者采用完全不同的方法。仔细看看,准备PrintSream并不是那么容易,也许我应该改用模拟对象?
编辑 :我想我应该 始终
专注于界面。从我的角度来看setTarget(),它也不是impl类的“合同”的一部分,它对依赖注入很有帮助。我认为从测试的角度来看,任何Impl类的公共方法都应视为私有方法。但是,这并不意味着我忽略了实现细节。
EDIT-2 在有多个实现\多个接口的情况下,我将测试所有实现,但是当我在setUp()方法中声明变量时,肯定会使用接口。