【问题标题】:Mocked function is not called, instead is used real function不调用模拟函数,而是使用真实函数
【发布时间】:2020-09-07 08:46:47
【问题描述】:

我开始学习嘲笑。我希望该测试在被调用时会失败(仅用于学习目的)。

MathUtils 类:

public class MathUtils {

  public int addWithHelper(int a, int b) {
        MathUtilsHelper mathUtilsHelper = new MathUtilsHelper();
        return mathUtilsHelper.addNumbers(a,b);
    }
}

还有我的 MathUtilsHelper:

public class MathUtilsHelper {

     int addNumbers(int a, int b) {
         return a + b;
     }
}

类 MathUtilsTest

@Test
void itShouldAddNumberFromHelper() {

     MathUtilsHelper mathUtilsHelperMocked = Mockito.mock(MathUtilsHelper.class);
     when(mathUtilsHelperMocked.addNumbers(5,3)).thenReturn(999); // this doesn't works !!!!!!

     int add = mathUtils.add(5, 3);
     assertEquals(8, add); // should throw error

}

感谢您的帮助!

【问题讨论】:

  • MathUtils 没有您创建的 MathUtilsHelper 的模拟实例。它有自己的MathUtilsHelper 实例,它使用new MathUtilsHelper() 创建自己。这就是我们使用依赖注入的原因

标签: java spring mocking mockito


【解决方案1】:

MathUtils 中没有模拟对象,您对 MathUtils 类执行以下操作:

public class MathUtils {
  public MathUtilsHelper mathUtilsHelper;

  public MathUtils(MathUtilsHelper mathUtilsHelper ){
     this.mathUtilsHelper=mathUtilsHelper;
  }

  public int addWithHelper(int a, int b) {
     return mathUtilsHelper.addNumbers(a,b);
  }
}

在初始化你的测试时试试这个:

@Test
void itShouldAddNumberFromHelper() {

   MathUtilsHelper mathUtilsHelperMocked = Mockito.mock(MathUtilsHelper.class);
   when(mathUtilsHelperMocked.addNumbers(5,3)).thenReturn(999);
   mathUtils= new MathUtils(mathUtilsHelperMocked);

   int add = mathUtils.addWithHelper(5, 3);
   assertEquals(8, add);

}

【讨论】:

  • 感谢您向我展示代码,但它仍然显示测试通过。预期值不是 999。
  • 测试中方法调用的名称错误,现在正确(add -> addWithHelper)。我已经测试了它适用于我的代码。请使用给定的更多内容检查您的实际代码。
【解决方案2】:

您的 util 类每次都会创建您的助手的新实例,因此永远不要使用模拟。

老实说,我不确定你为什么需要 util 类,但如果你想让它更容易测试,请更改它,以便在构造函数中传递帮助器的实例,而不是在实用程序类。换句话说就是依赖注入。

这样你就可以创建 mock,并通过传入 mock 来创建 util 类的实例。

【讨论】:

  • 好的,现在说得通了。所以当我想使用@Autowired(在常规应用程序中)时,我应该始终使用构造函数而不是字段,对吗?
  • 推荐使用构造函数注入,因为这意味着你不能创建一个没有依赖集的对象,你可以通过setter注入来做到这一点。此外,如果您使用 Spring 并且只有一个构造函数接收其他依赖项,即 Spring bean,则可以完全关闭自动装配注释,这很方便。
猜你喜欢
  • 1970-01-01
  • 2019-07-14
  • 1970-01-01
  • 2021-04-17
  • 1970-01-01
  • 2022-08-23
  • 1970-01-01
  • 2021-05-23
  • 1970-01-01
相关资源
最近更新 更多