我如何模拟本地最终变量
How can I mock a local final variable
我的方法中有一个局部变量,它是最终的。我该如何模拟?
public void method(){
final int i=myService.getNumber();
}
我要嘲讽
when(myService.getNumber()).thenReturn(1);
如何用mocking完成?
我的项目正在使用Java7,有没有办法使用反射或其他方式来实现这个mock
如前所述,这个请求没有多大意义。模拟系统不模拟变量(或字段)。但是,您可以轻松地将字段设置为您模拟的 object。您的测试将如下所示:
@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 void method(){
final int i=myService.getNumber();
}
我要嘲讽
when(myService.getNumber()).thenReturn(1);
如何用mocking完成?
我的项目正在使用Java7,有没有办法使用反射或其他方式来实现这个mock
如前所述,这个请求没有多大意义。模拟系统不模拟变量(或字段)。但是,您可以轻松地将字段设置为您模拟的 object。您的测试将如下所示:
@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) {
// ...
}