spring boot restful测试
基于spring boot 2.0.5.RELEASE
引入依赖
dependencies {
compile('org.springframework.boot:spring-boot-starter-web')
testCompile('org.springframework.boot:spring-boot-starter-test')
}
测试
控制层UserController.java
:
@RestController
public class UserController {
@RequestMapping(value = "/ping", method = RequestMethod.GET)
public String ping(){
return "ok";
}
}
测试基类:
@RunWith(SpringRunner.class)
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
public class WebSpringBootTest {
}
要测试rest,你必须通过指定@SpringBootTest
中的属性webEnvironment
来启动一个内置的servlet容器(embedded servlet container
)。默认的webEnvironment
的值是WebEnvironment.MOCK
,这个启动是没有带内置servlet容器的。在测试的时候可以指定以下Web环境:
- MOCK(默认)-
Loads a WebApplicationContext and provides a mock servlet environment. It will not start an embedded servlet container. If servlet APIs are not on your classpath, this mode will fall back to creating a regular non-web ApplicationContext
- RANDOM_PORT-加载
ServletWebServerApplicationContext
并启动一个内置的servlet容器监听在一个随机的端口 - DEFINED_PORT-加载
ServletWebServerApplicationContext
并启动一个内置的servlet容器监听在一个定义的端口(server.port) - NONE-使用
SpringApplication
加载ApplicationContext
,但不提供一个servlet环境
当@SpringBootTest
是内置了servlet容器启动的,那么就会自动注入TestRestTemplate
,建议使用WebEnvironment.RANDOM_PORT
,这样就不会和已有的端口冲突
import org.junit.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.web.client.TestRestTemplate;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import static org.assertj.core.api.Assertions.*; # 引入assertThat...
public class UserRestTest extends WebSpringBootTest {
@Autowired
private TestRestTemplate restTemplate;
@Test
public void pingTest(){
ResponseEntity<String> responseEntity = restTemplate.getForEntity("/ping", String.class);
assertThat(responseEntity.getStatusCode()).isEqualTo(HttpStatus.OK);
assertThat(responseEntity.getBody()).isEqualTo("ok");
}
}