spring boot项目测试controller和service的方法

测试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")
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

猜你喜欢

转载自blog.csdn.net/u013905744/article/details/81737803
今日推荐