Spring Boot Web API测试

来源:互联网 发布:软件开发cmm 编辑:程序博客网 时间:2024/06/06 03:54

第一步,在测试类外面加上如下注解:

@RunWith(SpringRunner.class)@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)

如果不是web,可以删掉webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT

第二步,web api如下:

@RequestMapping(value="/get1",method=RequestMethod.GET)public UserInfo get1(@RequestParam String name,@RequestParam String age){return userService.queryUserInfo(name, age);}

测试controller中的web api有两种方式,一种是直接注入该controller,然后像普通方法一样调用,另一种是通过TestRestTemplate,与RestTemplate用法一样,如果需要实现负载均衡,可以在配置类中重新配置该bean的实例化,如:

@Bean@LoadBalancedRestTemplate restTemplate() {return new RestTemplate();}

这里不需要负载均衡,所以无需上面的代码,测试代码如下:

    @Autowired    private TestRestTemplate restTemplate;    @Autowired    private UserController userController;    @Test    public void userTest() {    //方式一    UserInfo userInfo = restTemplate.getForObject("/get1?name={1}&age={2}", UserInfo.class, "李四", "24");        System.out.println(userInfo.toString());        //方式二        UserInfo user = userController.get1("对对对","12");        System.out.println(user.toString());    }

post请求也一样,通过TestRestTemplate的postForObject方法

注意要加上如下依赖:

<dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-test</artifactId><scope>test</scope></dependency>