测试controller
@RunWith(SpringRunner.class)
@SpringBootTest(classes = {MainApplication.class,MockServletContext.class})
public class ReindexTest {
private static final Logger LOGGER = LoggerFactory.getLogger(ReindexTest.class);
private MockMvc mockMvc;
@Autowired
private WebApplicationContext webApplicationContext;
@Before
public void setUp() {
mockMvc = MockMvcBuilders.webAppContextSetup(webApplicationContext).build();
}
@Test
public void testDeleteAllHistory() {
try {
MvcResult mvcResult = mockMvc.perform(MockMvcRequestBuilders.post("/es/deleteHistory").param("userId",
"419"))
.andReturn();
LOGGER.info(mvcResult.getResponse().getContentAsString());
} catch (Exception e) {
e.printStackTrace();
}
}
}
测试service
@RunWith(SpringRunner.class)
@SpringBootTest(classes = MainApplication.class)
@TestPropertySource(locations = "classpath:application-test.properties")
@ActiveProfiles("test")
public class ApplicationServiceTest {
@Autowired
private ApplicationService applicationService;
@Test
public void testSearchAppList() {
List<Application> list = applicationService.searchAppList("公积金", 1, 10);
System.out.println(list.size());
}
}
注意:@TestPropertySource注解用来指定其加载的properties文件,默认是application.properties
参考:java - Override default Spring-Boot application.properties settings in Junit Test - Stack Overflow
https://stackoverflow.com/questions/45659316/spring-boot-tests-cant-find-test-properties