简体   繁体   English

在Spring测试中模拟依赖的Autowired依赖

[英]Mocking an Autowired dependency of a dependency in Spring tests

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";
   }
}

I am trying to mock the method doD() in class D when calling method doA(); 我在尝试调用方法doA()时在类D中模拟方法doD(); However, I do not want to mock the doB() method in class B. Below is my test case. 但是,我不想模拟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();
  }
}

This still ends up returning "Hello" instead of "Ola". 这仍然最终返回“ Hello”而不是“ Ola”。 I tried @InjectMocks on A as well in the test class. 在测试类中,我也在A上尝试了@InjectMocks。 But that just results in the autowired B dependency B being null. 但这只会导致自动连线B依赖项B为空。 Is there something that's missing with my setup or is it the wrong way to go about this? 我的设置中是否缺少某些东西,或者这样做是错误的方式?

Thank you. 谢谢。

Use @MockBean as this will inject the mock bean into the application context before executing the test method docs . 使用@MockBean因为这将在执行测试方法docs之前将模拟bean注入到应用程序上下文中。

Annotation that can be used to add mocks to a Spring ApplicationContext. 可用于将模拟添加到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. 可用作类级别的注释或用作@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();
   }
}

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

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