maven依賴
< dependency>
< groupId> org.springframework.boot</ groupId>
< artifactId> spring-boot-starter-test</ artifactId>
< scope> test</ scope>
< exclusions>
< exclusion>
< groupId> junit</ groupId>
< artifactId> junit</ artifactId>
</ exclusion>
</ exclusions>
</ dependency>
< dependency>
< groupId> org.junit.platform</ groupId>
< artifactId> junit-platform-launcher</ artifactId>
< version> 1.5.2</ version>
< scope> test</ scope>
</ dependency>
< dependency>
< groupId> org.junit.jupiter</ groupId>
< artifactId> junit-jupiter-engine</ artifactId>
< version> 5.5.2</ version>
< scope> test</ scope>
</ dependency>
< dependency>
< groupId> org.junit.vintage</ groupId>
< artifactId> junit-vintage-engine</ artifactId>
< version> 5.5.2</ version>
< scope> test</ scope>
</ dependency>
< dependency>
< groupId> org.junit.jupiter</ groupId>
< artifactId> junit-jupiter-params</ artifactId>
< version> 5.5.1</ version>
< scope> test</ scope>
</ dependency>
< dependency>
< groupId> org.junit.jupiter</ groupId>
< artifactId> junit-jupiter-api</ artifactId>
< version> 5.5.2</ version>
< scope> test</ scope>
</ 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) ;
} ) ;
}