Reputation: 2056
I've generated a Spring Boot web application using Spring Initializer, embedded Tomcat, Thymeleaf template engine, and package as an executable JAR file.
Technologies used:
Spring Boot 1.4.2.RELEASE, Spring 4.3.4.RELEASE, Thymeleaf 2.1.5.RELEASE, Tomcat Embed 8.5.6, Maven 3, Java 8
I have these classes:
package com.tdk.helper;
@Component
public class BookMessageDecoder implements MessageDecoder {
private String messageData;
public BookMessageDecoder() {
super();
}
/**
* @param data4
*/
public BookMessageDecoder(String messageData) {
this.messageData=messageData;
}
..
}
@RestController
public class BookCallBackController {
BookSystemManager bookSystemManager;
@Autowired
BookMessageDecoder messageDecoder;
@Autowired
public BookCallBackController(BookSystemManager bookSystemManager) {
this.bookSystemManager = bookSystemManager;
}
..
}
@RunWith(SpringRunner.class)
public class BookCallBackControllerTests {
@MockBean
BookMessageDecoder messageDecoder;
private BookCallBackController controller;
@Before
public void setUp() throws Exception {
given(this.messageDecoder.hasAlarm()).willReturn(false);
controller = new BookCallBackController(new StubBookSystemManager());
}
..
}
Even I am mocking the bean bookMessageDecoder, is null when I use it !
Upvotes: 0
Views: 1064
Reputation: 2255
For Controller test you can always use springs @WebMvcTest(BookCallBackController.class)
annotations.
Also you need to configure a mockMvc for mock Http request to your controller.
After that you can autowire mockMvc @Autowired MockMvc mockMvc;
Now you can mock you dependency to controller @MockBean
BookMessageDecoder messageDecoder;
@RunWith(SpringRunner.class)
@WebMvcTest(BookCallBackController.class)
@AutoConfigureMockMvc
public class BookCallBackControllerTests {
@MockBean
BookMessageDecoder messageDecoder;
@Autowired
MockMvc mockMvc;
@Before
public void setUp() throws Exception {
given(this.messageDecoder.hasAlarm()).willReturn(false);
}
..
}
Upvotes: 1