例如,我有一个 java 类,如下所示。我要为 doWork() 编写一个单元测试,所以我想控制 obj 的行为。但是很明显obj是在内部实例化的。
这个UT怎么写?现在我正在使用 Junit+Mockito。
class ToBeTest{
public ToBeTest(){}
public boolean doWork(){
OtherObject obj=new OtherObject();
return obj.work();
}
}
提前致谢。 :)
顺便说一句,实际情况是我正在为其他人的类(class)编写 UT。所以我不想改变它。已通过集成测试全面测试。
最佳答案
如果您无法更改代码,您可以使用 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"));
}
关于java - 如何编写 UT 以一种方法模拟内部对象?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7440946/