- 在http://start.spring.io/ 选择要测试的SpringBoot版本,这里选择“1.5.4.RELEASE”。
- 选择需要添加的模块依赖:选择spring-boot-starter-actuator和spring-boot-starter-test
- 点击生成项目按钮
- 解压项目压缩包
- 导入IDEA
- 在src/java 目录下新建具体的测试Controller,如创建HelloWorldController.java 测试Controller:
package com.example.springbootjunittest.controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
/**
* HelloWorld 测试控制器
*
* @author <a href="mailto:[email protected]">strongant</a>
* @see
* @since 2017/8/20
*/
@RestController
public class HelloWorldController {
@RequestMapping(value = "/")
public String index() {
return "Hello World";
}
}
- (可选)修改默认的8080端口,这里设置为9999,只需要在项目的src/main/resources/application.properties文件中添加如下一行即可:
server.port= 9999
- 在生成的SpringbootJunitTestApplicationTests.java文件中修改如下
:
package com.example.springbootjunittest;
import com.example.springbootjunittest.controller.HelloWorldController;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.test.web.client.TestRestTemplate;
import org.springframework.http.MediaType;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.request.MockMvcRequestBuilders;
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
import static org.assertj.core.api.Java6Assertions.assertThat;
import static org.hamcrest.core.IsEqual.equalTo;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
@RunWith(SpringRunner.class)
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
public class SpringbootJunitTestApplicationTests {
@Autowired
private TestRestTemplate restTemplate;
private MockMvc mvc;
@Before
public void setUp() throws Exception {
mvc = MockMvcBuilders.standaloneSetup(new HelloWorldController()).build();
}
@Test
public void sayHello() throws Exception {
mvc.perform(MockMvcRequestBuilders.get("/").accept(MediaType.APPLICATION_JSON))
.andExpect(status().isOk())
.andExpect(content().string(equalTo("Hello World")));
}
@Test
public void exampleTest() {
String body = this.restTemplate.getForObject("/", String.class);
assertThat(body).isEqualTo("Hello World");
}
@Test
public void contextLoads() {
}
}
- 运行即可,测试输出是否与期望一致。