[英]How can I mock a local final variable
我的方法中有一個局部變量是最終的。 我該如何嘲笑?
public void method(){
final int i=myService.getNumber();
}
我想嘲笑
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) {
// ...
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.