Reputation: 783
I wrote simple spring boot application with Controller
, Service
and Business
classes, but while writing integration test the mock method of Service
is returning null
MockMainController
@RestController
public class MockMainController {
@Autowired
private MockBusiness mockBusiness;
@GetMapping("request")
public MockOutput mockRequest() {
return mockBusiness.businessLogic(new MockInput());
}
}
MockBusiness
@Service
public class MockBusiness {
@Autowired
private MockService mockService;
public MockOutput businessLogic(MockInput input) {
return mockService.serviceLogic(input);
}
}
MockService
@Service
public class MockService {
@Autowired
private MockUtil mockUtil;
public MockOutput serviceLogic(MockInput input) {
mockUtil.exchange(UriComponentsBuilder.fromUriString(" "), HttpMethod.GET, HttpEntity.EMPTY,
new ParameterizedTypeReference<MockOutput>() {
});
return new MockOutput();
}
}
I'm trying to mock the MockService
bean in application context using @MockBean
MockControllerTest
@SpringBootTest
@ActiveProfiles("test")
@Profile("test")
@RunWith(SpringJUnit4ClassRunner.class)
public class MockControllerTest {
@Autowired
private MockMainController mockMainController;
@MockBean
private MockService mockService;
@Test
public void controllerTest() {
MockOutput output = mockMainController.mockRequest();
given(this.mockService.serviceLogic(ArgumentMatchers.any(MockInput.class)))
.willReturn(new MockOutput("hello", "success"));
System.out.println(output); //null
}
}
In the test method I created mock service bean using @MockBean
I'm not having any error here but System.out.println(output);
prints null
Upvotes: 2
Views: 2892
Reputation: 330
You are getting null
because of wrong statements order in your test method. You first call controller method and you get what's inside default @MockBean
which is in this case null
. Swap statement:
MockOutput output = mockMainController.mockRequest();
with
given(this.mockService.serviceLogic(ArgumentMatchers.any(MockInput.class)))
.willReturn(new MockOutput("hello", "success"));
and you will get expected result.
Upvotes: 2