【问题标题】:Mocking an Autowired dependency of a dependency in Spring tests在 Spring 测试中模拟依赖项的自动装配依赖项
【发布时间】:2019-03-13 03:58:02
【问题描述】:

我试图在我的测试中模拟一个依赖项的依赖项。下面是我的类的样子。

class A {
  @Autowired B b;
  @Autowired C c;

  public String doA() {

    return b.doB() + c.doC();
  }
}

class C {
  @Autowired D d;

  public String doC() {

    return d.doD();
  }
}

class D {

   public String doD() {

      return "Hello";
   }
}

我试图在调用方法 doA() 时模拟 D 类中的方法 doD(); 但是,我不想模拟 B 类中的 doB() 方法。 下面是我的测试用例。

@RunWith(SpringRunner.class)
@SpringBootTest(
  classes = MyTestApplication.class,
  webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT
)
public class ATest {

  @Autowired
  private A a;

  @InjectMocks
  @Spy
  private C c;

  @Mock
  private D d;

  @Before
  public void setUp() throws Exception {
    MockitoAnnotations.initMocks(this);
  }

  @Test
  public void testDoA() {

    doReturn("Ola")
      .when(d)
      .doD();

    a.doA();
  }
}

这仍然会返回“Hello”而不是“Ola”。 我在 A 上也尝试了 @InjectMocks 以及在测试类中。但这只会导致自动装配的 B 依赖项 B 为空。 我的设置是否缺少某些东西,或者这是错误的方法?

谢谢。

【问题讨论】:

    标签: java spring mockito


    【解决方案1】:

    使用@MockBean,因为这将在执行测试方法docs之前将模拟bean注入应用程序上下文。

    可用于向 Spring ApplicationContext 添加模拟的注解。可以用作类级别的注解或@Configuration 类中的字段,或者是@RunWith SpringRunner 的测试类。

    @RunWith(SpringRunner.class)
    @SpringBootTest(
    classes = MyTestApplication.class,
    webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
    
      public class ATest {
    
      @Autowired
      private A a;
    
      @MockBean
      private D d;
    
      @Test
      public void testDoA() {
    
       doReturn("Ola")
          .when(d)
          .doD();
    
        a.doA();
       }
    }
    

    【讨论】:

      猜你喜欢
      • 2016-09-23
      • 1970-01-01
      • 2021-10-19
      • 2018-03-28
      • 1970-01-01
      • 2020-12-02
      • 1970-01-01
      • 2021-12-03
      • 1970-01-01
      相关资源
      最近更新 更多