我的方法中有一个局部变量,它是最终的。我该如何 mock ?
public void method(){
final int i=myService.getNumber();
}
我想 mock
when(myService.getNumber()).thenReturn(1);
如何通过模拟来完成它?
我的项目使用的是Java 7,有没有办法使用反射或其他方式来实现这个模拟
最佳答案
如前所述,这个请求没有多大意义。模拟系统不会模拟变量(或字段)。但是,您可以轻松地将字段设置为您模拟的对象。您的测试将如下所示:
@Test public void methodWithNumberOne {
MyService myService = Mockito.mock(MyService.class);
when(myService.getNumber()).thenReturn(1);
// You might want to set MyService with a constructor argument, instead.
SystemUnderTest systemUnderTest = new SystemUnderTest();
systemUnderTest.myService = myService;
systemUnderTest.method();
}
<小时/>
另一种不需要模拟的设置方法:
public void method() {
method(myService.getNumber());
}
/** Use this for testing, to set i to an arbitrary number. */
void method(final int i) {
// ...
}
关于java - 如何模拟局部最终变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31884014/