繁体   English   中英

新实例上的模拟方法

[英]Mock method on a new instance

我正在尝试使用 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;
      }
   }

我有一个像上面一样的 class 结构,我需要模拟 secondMethod。

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

注意 - 我不在 position 中更改 class 的结构。

你有一些选择:

  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设置器仅用于测试。
   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);

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM