spring boot restful测试

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");
    }

}
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值