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

Logo

魔乐社区(Modelers.cn) 是一个中立、公益的人工智能社区,提供人工智能工具、模型、数据的托管、展示与应用协同服务,为人工智能开发及爱好者搭建开放的学习交流平台。社区通过理事会方式运作,由全产业链共同建设、共同运营、共同享有,推动国产AI生态繁荣发展。

更多推荐