java - 如何模拟局部最终变量

标签 java unit-testing reflection mockito

我的方法中有一个局部变量,它是最终的。我该如何 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/

相关文章:

C# - 制作一个接受任何类型的通用 foreach 方法?

java - 如何在 Java Reflections 中声明类之外加载类函数

java - 我可以使用 Hamcrest 的 Matchers.containsInRelativeOrder 吗?

java - 如何设置ListView水平滚动?

java - pom为3个应用程序使用Spring-mvc的公共(public)依赖

java - if 条件被忽略

c++ - 设置单元测试需要多少个项目

c# - 如何模拟存储库/工作单元

python - 使用 unittest.mock 在 python 中修补 SMTP 客户端

python - 从函数内获取输入变量的名称