SpringBoot 2.x 单元测试(junit5)

maven依赖

     <dependency>
            <groupId>org.springframework.bootgroupId>
            <artifactId>spring-boot-starter-testartifactId>
            <scope>testscope>
            <exclusions>
                <exclusion>
                    <groupId>junitgroupId>
                    <artifactId>junitartifactId>
                exclusion>
            exclusions>
        dependency>
        
      <dependency>
            <groupId>org.junit.platformgroupId>
            <artifactId>junit-platform-launcherartifactId>
            <version>1.5.2version>
            <scope>testscope>
        dependency>
        <dependency>
            <groupId>org.junit.jupitergroupId>
            <artifactId>junit-jupiter-engineartifactId>
            <version>5.5.2version>
            <scope>testscope>
        dependency>
        <dependency>
            <groupId>org.junit.vintagegroupId>
            <artifactId>junit-vintage-engineartifactId>
            <version>5.5.2version>
            <scope>testscope>
        dependency>
        <dependency>
            <groupId>org.junit.jupitergroupId>
            <artifactId>junit-jupiter-paramsartifactId>
            <version>5.5.1version>
            <scope>testscope>
        dependency>
        <dependency>
            <groupId>org.junit.jupitergroupId>
            <artifactId>junit-jupiter-apiartifactId>
            <version>5.5.2version>
            <scope>testscope>
        dependency>

Service测试

import static org.junit.jupiter.api.Assertions.assertTrue;

@Profile("dev")
@ExtendWith(SpringExtension.class)
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
@TestInstance(TestInstance.Lifecycle.PER_CLASS)
public class DemoServiceImplTest {

    @Autowired
    private DemoService demoService;

    @RepeatedTest(3)
    public void qryDemo() {
        List list = demoService.qryDemo(null,1,5);
        assertTrue(!list.isEmpty(), "列表为空");
    }
}

Controller测试

@Profile("dev")
@ExtendWith(SpringExtension.class)
@SpringBootTest
@AutoConfigureMockMvc
@Slf4j
public class Oauth2ControllerTest {

    @Autowired
    private MockMvc mockMvc;

	 @Test
    public void user() throws Exception {
        String jwtToken = "abcdefghijklmn";

            mockMvc.perform(MockMvcRequestBuilders.get("/a/b/c")
                .header(SecurityConstants.JWT_HEADER_AUTHORIZATION_CODE, jwtToken)
                .param("name","trump")
                .accept(MediaType.APPLICATION_JSON))
                .andExpect(status().isOk())
                .andDo(result -> {
                    String json = result.getResponse().getContentAsString();

                    log.info("获取响应信息为:\n" + json);
                });
}

你可能感兴趣的:(#,spring-boot,测试)