如何模拟一个spring bean以及它的autowired ctor参数?

时间:2017-08-05 00:54:15

标签: java spring unit-testing spring-boot mockito

我想模拟一个对象和一个自动构建的依赖项。

E.g:

class MyTest {
  @MockBean A a;
  @Test myTest() {
    assertTrue(when(a.some()).thenCallRealMethod());
  }
}
@Component
class A {
  private B b;
  A(B dependency) {
    this.b = dependency;
  }
  boolean some() {
    return b.value();
  }
}
@Configuration
class B {
  boolean value() { return true; }
}

这会在a::some中调用MyTest::myTest时抛出NPE。 我如何模拟模拟依赖项?

1 个答案:

答案 0 :(得分:2)

首先,你必须选择跑步者,

SpringRunner或Mockito Runner

在这种情况下,我选择了SpringRunner: 文档:https://docs.spring.io/spring/docs/current/javadoc-api/org/springframework/test/context/junit4/SpringRunner.html

然后你创建了一个A的MockBean,你必须定义模拟行为

when(a.some()).thenReturn(true);

@RunWith(SpringRunner.class)
    public class MyTest {

         @MockBean A a;

         @Test
         public void  myTest() {
            when(a.some()).thenReturn(true);
            assertTrue(a.some());

        }
        @Component
        class A {
          private B b;
          A(B dependency) {
            this.b = dependency;
          }
          boolean some() {
            return b.value();
          }
        }
        @Configuration
        class B {
          boolean value() { return true; }
        }

    }

使用@SpyBean测试Real方法:

@RunWith(SpringRunner.class)
@SpringBootTest(classes={MyTest.class,MyTest.B.class,MyTest.A.class})
public class MyTest {

     @SpyBean A a;

     @Test
     public  void  myTest() {

       assertTrue(a.some());

    }
    @Component
    class A {
      private B b;
      A(B dependency) {
        this.b = dependency;
      }
      boolean some() {
        return b.value();
      }
    }
    @Configuration
    class B {


      boolean value() { return true; }
    }

}

监视A并嘲笑B将如下所示:

@RunWith(SpringRunner.class)
@SpringBootTest(classes={MyTest.class,MyTest.B.class,MyTest.A.class})
public class MyTest {

     @SpyBean A a;

     @MockBean B b;

     @Test
     public  void  myTest() {

         when(b.value()).thenReturn(false);
       assertTrue(a.some());

    }
    @Component
    class A {
      private B b;
      A(B dependency) {
        this.b = dependency;
      }
      boolean some() {
        return b.value();
      }
    }
    @Configuration
    class B {


      boolean value() { return true; }
    }

}

结果:断言失败,因为B的模拟行为是错误的。