Reputation: 903
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.
Upvotes: 0
Views: 861
Reputation: 40008
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();
}
}
Upvotes: 1