我的方法中有一个局部变量,它是最终的。我该如何嘲笑?
public void method(){
final int i=myService.getNumber();
}
我想嘲笑
when(myService.getNumber()).thenReturn(1);
如何通过mocking完成它?
我的项目正在使用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) {
// ...
}
public static final RestTemplate REST_TEMPLATE = new RestTemplate(new SimpleClientHttpRequestFactory());
请帮助我。