在 Spring 测试中模拟依赖项的自动装配依赖项 [英] Mocking an Autowired dependency of a dependency in Spring tests

查看:57
本文介绍了在 Spring 测试中模拟依赖项的自动装配依赖项的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图在我的测试中模拟依赖项的依赖项.下面是我的课程的样子.

I am trying to mock a dependency of a dependency in my tests. Below is what my classes look like.

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() 方法.下面是我的测试用例.

I am trying to mock the method doD() in class D when calling method doA(); However, I do not want to mock the doB() method in class B. Below is my test case.

@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 为空.我的设置中是否缺少某些东西,或者这是解决此问题的错误方法?

This still ends up returning "Hello" instead of "Ola". I tried @InjectMocks on A as well in the test class. But that just results in the autowired B dependency B being null. Is there something that's missing with my setup or is it the wrong way to go about this?

谢谢.

推荐答案

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

Use @MockBean as this will inject the mock bean into the application context before executing the test method docs.

可用于向 Spring ApplicationContext 添加模拟的注解.可用作类级别注释或@Configuration 类或@RunWith SpringRunner 的测试类中的字段.

Annotation that can be used to add mocks to a Spring ApplicationContext. Can be used as a class level annotation or on fields in either @Configuration classes, or test classes that are @RunWith the 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();
   }
}

这篇关于在 Spring 测试中模拟依赖项的自动装配依赖项的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆