简体   繁体   中英

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(); 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();
  }
}

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?

Thank you.

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

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();
   }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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