新实例上的模拟方法

问题描述 投票:0回答:2

我正在尝试使用 Mockito 框架和 junit5 创建 Junit 测试用例。我正在编写以下代码:

    Class ClasstToBeTested {
      FirstClass a = new FirstClass();

      public String methodToBeTested() {
         String str = a.firstMethod();
         return str;
      }
    }

   Class FirstClass {
      SecondClass b = new SecondClass();

      public String firstMethod() {
          String str = b.secondMethod();
          return str;
      }
   }

我有一个像上面这样的类结构,我需要模拟第二个方法。

我在 FirstClass 上尝试了 @spy 并模拟了 SecondClass 和 secondaryMethod,但模拟并没有发生。在这种情况下我该如何嘲笑?

注意 - 我无法更改班级的结构。

java mockito junit5
2个回答
1
投票

您有一些选择:

  1. (首选)使用 IoC 依赖注入来提供
    SecondClass
    实例,而不是在
    FirstClass
    内部构建它:
  class FirstClass {
      private final SecondClass b;

      // Injecting the SecondClass instance
      FistClass(SecondClass b) {
          this.b = b;
      }

      public String firstMethod() {
          String str = b.secondMethod();
          return str;
      }
   }

然后你可以在测试中注入模拟。

  1. 添加一个
    SecondClass
    setter 仅用于测试。
   class FirstClass {
      SecondClass b = new SecondClass();

      // Annotate with a visibility for test annotation if available.
      // Here one can inject a mock too, but can cause problems if used inadvertently.
      void setSecondClassForTests(SecondClass b) {
         this.b = b;
      }

      public String firstMethod() {
          String str = b.secondMethod();
          return str;
      }
   }

然后您在测试中调用 setter 并通过模拟。

  1. 使用反射来获取字段并设置模拟。像(在你的测试函数中):
final Field declaredField = instanceOfFirstClass.getClass().getDeclaredFields("b");
declaredField.setAccessible(true);
declaredField.set(instanceOfFirstClass, yourMockedInstance);

0
投票

最新版本的mockito支持模拟构造函数

参考:使用 Mockito 模拟局部范围对象的方法

© www.soinside.com 2019 - 2024. All rights reserved.