Spring boot integrates junit4 1.0 - Test API
1. Project configuration:
Import dependencies: pom.xml
<dependencies>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
</dependency>
</dependencies>
spring-boot-starter-test
: is used to test the api request.
Test class: apiTest.java
import xxx.inte.xxxApplication;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.context.web.WebAppConfiguration;
/**
* @Description a simple test class for user apis
* @Author Lanye
**/
@RunWith(SpringJUnit4ClassRunner.class)
@SpringBootTest(classes = xxxApplication.class)
@WebAppConfiguration
public class userApiTest {
@Test
public void create(){
}
}
An initial example is over.
2. Test API:
- Let me take a look at the API to test:
@PostMapping("/create")
public void create(SysUserEntity sysUser){
//...
}
- We can find it’s a post request.
@Test
public void create(){
try {
String url = "http://localhost:8090/sys_user/create";
MultiValueMap<String, Object> map = new LinkedMultiValueMap<>();
map.add("usemame", "lanye");
//...
RestTemplate template = new RestTemplate();
String result = template.postForObject(url, map, String.class);
System.out.println(result);
}catch (Exception e){
e.printStackTrace();
}
}
- The test is successful, the effect diagram is not on. If it’s a get request:
template.getForObject(url, String.class, map);
3. Tips:
- template.getForObject() and .postForObkect() return type is not String but
<T>
, using<T>
without casting is safer at compile than Object;