使用 junit 对 springboot 应用进行单元测试 使用 springboot 2.2.5 开发 web 应用的时候,需要进行单元测试。 普通的 java 的单元测试比较简单,对于采用 REST 方式开发的微服务,则需要使用 WEB 环境进行测试。 示例代码如下: package com.sample.api; import com.sample.api.controller.TestController; import com.sample.api.entity.User; import org.junit.Assert; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.boot.test.web.client.TestRestTemplate; import org.springframework.test.context.junit4.SpringRunner; import javax.annotation.Resource; @RunWith(SpringRunner.class) @SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.DEFINED_PORT) public class TestControllerTest { @Resource private TestRestTemplate restTemplate; @Test public void test(){ User user = restTemplate.getForObject("/users/abc", User.class); System.out.println(user); Assert.assertNotNull(user); Assert.assertEquals("abc", user.getUsername()); } } 需要注意的是对于 SpringBoot 里……

阅读全文