Springboot webController UnitTest
how to test web api in unit test?
– use mockMVC and springbootTest
@RunWith(SpringRunner.class)
@SpringBootTest
@EnableWebMvc
@AutoConfigureMockMvc
public class WebServiceTest extends TestCase {
@Resource
private YourService yourservice;
@InjectMocks
private YourControlelr yourController;
@Autowired
private WebApplicationContext webApplicationContext;
protected MockMvc mockMvc;
private String prefix = "http://host:prot/yourPrefix";
@Before
public void setUp() throws Exception {
webService = new WebService();
webService.setYourService(yourservice);
MockMvcBuilders.webAppContextSetup(webApplicationContext);
mockMvc=MockMvcBuilders.standaloneSetup(webService).build();
}
@Test
public void yourApiMethod() {
ResultActions resultActions = null;
MockHttpServletRequestBuilder mockHttpServletRequestBuilder = MockMvcRequestBuilders.get(prefix+"/yourmethodurl" );
try {
resultActions = mockMvc.perform( mockHttpServletRequestBuilder );
resultActions.andReturn().getResponse().getOutputStream().println();
System.out.println(resultActions.andReturn().getResponse().getStatus());
} catch (Exception e) {
e.printStackTrace();
}
}
}