RRZ*_*ope 4 java junit mockito
对单元测试和模拟非常新,我有一个方法来测试它在新对象上调用方法。我怎样才能模拟内部对象?
methodToTest(input){
...
OtherObject oo = new OtherObject();
...
myresult = dosomething_with_input;
...
return myresult + oo.methodX();
}
Run Code Online (Sandbox Code Playgroud)
我可以模拟 oo 返回“abc”吗?我真的只想测试我的代码,但是当我模拟“methodToTest”返回“42abc”时,我不会测试我的“dosomething_with_input”代码......
我认为实现的类methodToTest被命名ClassToTest
OtherObjectClassToTestClassToTest ClassToTest对象时初始化它并为工厂创建一个setter你的测试类应该看起来像
public class ClassToTestTest{
@Test
public void test(){
// Given
OtherObject mockOtherObject = mock(OtherObject.class);
when(mockOtherObject.methodX()).thenReturn("methodXResult");
OtherObjectFactory otherObjectFactory = mock(OtherObjectFactory.class);
when(otherObjectFactory.newInstance()).thenReturn(mockOtherObject);
ClassToTest classToTest = new ClassToTest(factory);
// When
classToTest.methodToTest(input);
// Then
// ...
}
}
Run Code Online (Sandbox Code Playgroud)