码迷,mamicode.com
首页 > 编程语言 > 详细

Spring boot 1.4.2 单元测试配置

时间:2016-11-24 19:18:43      阅读:311      评论:0      收藏:0      [点我收藏+]

标签:cat   bsp   res   pre   blog   tco   ini   rpo   cep   

新版较旧版简化了很多

直接在测试类上添加

@RunWith(SpringRunner.class)
@SpringBootTest(classes = 自己的启动类, webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)

同事注入 TestRestTemplate类 和通过 @LocalServerPort注解注入当前的端口号

具体测试代码如下:

@RunWith(SpringRunner.class)
@SpringBootTest(classes = ServerApplication.class, webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
public class Test {


    @LocalServerPort
    private int port;

    private URL base;
    private Gson gson = new Gson();

    @Autowired
    private TestRestTemplate restTemplate;

    @Before
    public void setUp() throws Exception {
        this.base = new URL("http://localhost:" + port + "/");
    }

    @Test
    public void test() {
        ResponseEntity<String> test = this.restTemplate.getForEntity(
                this.base.toString() + "/test", String.class, "test");
        System.out.println(test.getBody());
    }
}

 controller

@RestController
@RequestMapping("/test")
public class ProcessInstanceController {

    @RequestMapping(value = "", method = RequestMethod.GET)
    public String test() {
        return "Greetings from Spring Boot!";
    }
}
ServerApplication:
@SpringBootApplication
public class ServerApplication extends SpringBootServletInitializer implements CommandLineRunner {


    @Override
    protected SpringApplicationBuilder configure(SpringApplicationBuilder application) {
        return application.sources(ServerApplication.class);
    }


    public static void main(String[] args) throws IOException {
        SpringApplication.run(ServerApplication.class, args);
    }


    @Override
    public void run(String... strings) throws Exception {

        System.out.println("初始化。。。。。。。。。。。。");
    }
}

 

Spring boot 1.4.2 单元测试配置

标签:cat   bsp   res   pre   blog   tco   ini   rpo   cep   

原文地址:http://www.cnblogs.com/ButterFuture/p/6098692.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!