我是Spring Boot的新手,并试图了解如何在Spring Boot中完成测试。我读到了@SpringBootTest注释,它有助于集成测试应用程序。我想知道如何在春季启动时进行单元测试。单元测试是否需要指定@SpringBootTest注释,还是仅用于集成测试?是否有用于单元测试的特定注释?
任何指针都会非常感激。提前谢谢!
编辑: SpringBootTest注释是否仅用于集成测试?我在Spring文档中找到了以下代码示例:
@RunWith(SpringRunner.class)
@SpringBootTest
@AutoConfigureMockMvc
public class HelloControllerTest {
@Autowired
private MockMvc mvc;
@Test
public void getHello() throws Exception {
mvc.perform(MockMvcRequestBuilders.get("/").accept(MediaType.APPLICATION_JSON))
.andExpect(status().isOk())
.andExpect(content().string(equalTo("Greetings from Spring Boot!")));
}
}
这是一个单元还是集成测试?我的猜测是它不是集成测试,因为它使用了MockMvc。是对的吗?如果是这样,这是否意味着@SpringBootTest注释可用于未完全成熟的集成测试的测试?
答案 0 :(得分:0)
严格来说,“单位”测试不应该使用Spring。只需像往常一样使用JUnit / TestNG / Spock /其他任何东西来测试各个类。 @SpringBootTest用于集成,以及测试。
答案 1 :(得分:0)
这就是我要做的: 对于端到端集成测试:
@RunWith(SpringRunner.class)
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
public class ApplicationTests {
@Autowired
private TestRestTemplate restTemplate;
@Autowired
private CarRepository repository;
@Autowired
private CarService carService;
@Test
public void contextLoads() {
}
@Test
public void basicTest() {
String body = this.restTemplate.getForObject("/", String.class);
assertThat(body).contains("Not Found");
}
}
仅用于测试控制器(控制器单元测试):
@RunWith(SpringRunner.class)
@WebMvcTest(controllers = CarController.class, excludeAutoConfiguration = EmbeddedMongoAutoConfiguration.class)
public class ControllerTests {
@Autowired
private MockMvc mvc;
@MockBean
private CarRepository carRepository;
@MockBean
private MongoTemplate mongoTemplatel;
@Test
public void testGet() throws Exception {
short year = 2010;
given(this.carRepository.findByVin("ABC"))
.willReturn(new Car("ABC", "Honda", "Accord", year, 100000, "Red", "Ex-V6"));
this.mvc.perform(get("/car").param("VIN", "ABC").accept(MediaType.APPLICATION_JSON))
.andExpect(status().isOk()).andExpect(content().string("[{\"vin\":\"ABC\",\"make\":\"Honda\",\"model\":\"Accord\",\"year\":2010,\"mileage\":100000,\"color\":\"Red\",\"trim\":\"Ex-V6\",\"type\":null,\"maintenanceTasksList\":[\"Oil Change\",\"Tire Rotation\"]}]"));
}
}
您可以找到包含集成和单元测试here的完整Spring Boot应用程序。