首页 > 代码库 > 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 单元测试配置