首页 > 代码库 > Spring boot 1.4.2 单元测试配置
Spring boot 1.4.2 单元测试配置
新版较旧版简化了很多
直接在测试类上添加
@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 单元测试配置
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。