第一种方式直接调用controller
Result result = testApiController.test("hello,this is my test info");
Assert.assertTrue(result.isOk());
第二种:通过rest template ,post提交如下
HttpHeaders headers = new HttpHeaders();
headers.add("param1", "ikong");
headers.add("param2", "16070");
Map<String, String> map = new HashMap<>();
map.put("body", "{'name':'ikong'}");
HttpEntity entity = new HttpEntity<>("{'name':'ikong'}", headers);
Result result = restTemplate.postForObject("/api/test", entity, Result.class, map);
System.out.println(JSON.toJSONString(result));
Assert.assertTrue(result.isOk());
注意事项,某些test case 是有顺序的,我们需要jvm按照代码行的顺序从上到下执行单元测试,
@SpringBootTest(classes = TestApplication.class, webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
@RunWith(SpringRunner.class)
@FixMethodOrder(MethodSorters.JVM)
public class MessageApiTest {
}
重点就是这里:@FixMethodOrder(MethodSorters.JVM)
工程pom引入
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<version>2.1.6.RELEASE</version>
<scope>test</scope>
</dependency>