Sma*_*key 13 java unit-testing
例如,我有一个java类,如下所示.我将为doWork()编写一个单元测试,所以我想控制obj的行为.但很明显,obj是在内部实例化的.
我怎么写这个UT?现在我正在使用Junit + Mockito.
class ToBeTest{
public ToBeTest(){}
public boolean doWork(){
OtherObject obj=new OtherObject();
return obj.work();
}
}
Run Code Online (Sandbox Code Playgroud)
提前致谢.:)
顺便说一句,现实是我正在为其他人的班级写UT.所以我不想改变它.它已通过集成测试进行了全面测试.
dMc*_*ish 10
如果您无法更改代码,可以使用Powermock以及junit和Mockito来模拟新对象的构造.
@Test
public void testDoWork() throws Exception{
MyTest mytest = new MyTest();
OtherObj obj = new OtherObj();
obj.test="mocked Test"; //here you can add any other needed values to obj
PowerMockito.whenNew(OtherObj.class).withNoArguments().thenReturn(obj);
String result = mytest.doWork();
Assert.assertTrue(result.equalsIgnoreCase("mocked Test"));
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
6043 次 |
| 最近记录: |