假设您有一个实现它的接口和一个实现类,并希望为此编写单元测试。 我应该测试哪个接口或Impl?
这是一个例子:
公共接口hello接口{
public void sayHello (;
}
publicclasshellointerfaceimplimplementshellointerface {
privateprintstreamtarget=system.out;
@Override
公共void say hello () {
target.print(Helloworld );
}
publicvoidsettarget (打印流目标) )。
this.target=target;
}
}
因此,我有hello接口和HelloInterfaceImpl来实现它。 什么是被测单元接口或Impl?
我觉得是hello接口。 请考虑一下JUnit测试草图。
公共类hellointerfacetest {
专用hello接口hi;
@Before
公共void setup () }
hi=new HelloInterfaceImpl (;
}
@Test
publicvoidtestdefaultbehaviourendsnormally (
hi.sayHello (;
//no NullPointerException here
}
@Test
公共void testcheckhelloworld () throws Exception { )。
bytearrayoutputstreamout=newbytearrayoutputstream (;
printstream target=new printstream (out;
privilegedaccessor.setvalue(hi,' target ',target;
//youcanusereflectiontestutilsinplaceofprivilegedaccessor
//really it is DI
//() hellointerfaceimpl ) hi ).settarget );
hi.sayHello (;
String result=out.toString (;
资产质量(hello world )、结果);
}
}
主线其实是我注释的线。
(HelloInterfaceImpl ) hi ).settarget );
方法setTarget () )不是我公共接口的一部分,所以我不想意外
来修改选定线条的属性。 如果我真的想给我打电话的话,应该花点时间考虑。 例如,它能帮助我发现我真正想做的是依赖注入。 它为我打开了新的机会世界。 我可以使用一些现有的依赖注入机制。 例如,Spring依赖注入机制。 我可以像在代码中实际做的那样自己模拟它,也可以采用完全不同的方法。 仔细看。 准备打印流没那么容易。 也许应该切换到模拟对象吗?
编辑:我总是
集中在界面上。 从我的角度来看,setTarget ()也不是impl类“合同”的一部分,有助于依赖注入。 从测试的角度来看,我认为任何Impl类的公共方法都应该被视为私有方法。 但这并不意味着我忽略了实现的细节。
EDIT-2实现如果有多个接口,它将测试所有实现,但在setUp ()方法中声明变量时,它始终使用接口。