带有模拟的 MvcTest 是集成测试或单元测试
Posted
技术标签:
【中文标题】带有模拟的 MvcTest 是集成测试或单元测试【英文标题】:MvcTest with mocks is integration test or unit test 【发布时间】:2021-11-07 12:08:24 【问题描述】:如果我们在休息端点上的MvcMock
测试中有模拟,我们可以将其称为integration test
吗?当然,我可以说TestRestTemplate
测试是integration test
,因为在我测试端点时没有模拟。
MvcMock test
@SpringBootTest
@AutoConfigureMockMvc
@ActiveProfiles("test")
internal class CreateProductRestControllerMvcTest
@Autowired
private lateinit var mockMvc: MockMvc
@Autowired
private lateinit var objectMapper: ObjectMapper
@MockkBean
private lateinit var createProductService: CreateProductService
@ParameterizedTest
@ArgumentsSource(ValidCreateProductRequests::class)
internal fun `POST a new Product, GIVEN without any exception, THEN return Product id and status 201`(request: CreateProductRequest)
// Given
every createProductService.invoke(request.toCommand()) returns ProductId(1L)
// When, Then
this.mockMvc.post(REST_PRODUCTS)
contentType = APPLICATION_JSON
content = objectMapper.writeValueAsString(request)
.andExpect
status isCreated()
content json((objectMapper.writeValueAsString(1L)))
TestRestTemplate Test
@SpringBootTest(webEnvironment = RANDOM_PORT, classes = [Application::class])
@ActiveProfiles("test")
@Testcontainers
@FlywayTest
@ExtendWith(FlywayTestExtension::class)
class CreateProductRestControllerIntegrationTest
@Autowired
private lateinit var restTemplate: TestRestTemplate
private lateinit var headers: HttpHeaders
@BeforeEach
internal fun setUp()
headers = HttpHeaders()
headers.contentType = MediaType.APPLICATION_JSON
@FlywayTest
@ParameterizedTest
@ArgumentsSource(ValidJsonRequestBodies::class)
internal fun `POST new Product, GIVEN valid request, THEN returns 201`(json: String)
// Given
val request: HttpEntity<String> = HttpEntity(json, headers)
// When
val result = restTemplate.postForEntity(REST_PRODUCTS, request, String::class.java);
// Then
assertNotNull(result.body)
assertEquals(HttpStatus.CREATED, result.statusCode)
【问题讨论】:
【参考方案1】:在我看来,将其称为“集成测试”并不完全公平。通过模拟服务,您基本上是在测试您的控制器并测试序列化和反序列化 JSON 的能力,这是一个完全有效的测试。
在 Spring 世界中,您可能会发现这些被称为“切片测试”,其中测试的目的是检查应用程序的给定层,而不是完全成熟的集成测试。有关它们的更多信息:
https://docs.spring.io/spring-boot/docs/2.1.5.RELEASE/reference/html/boot-features-testing.html#boot-features-testing-spring-boot-applications-testing-autoconfigured-tests https://www.baeldung.com/spring-tests#5-using-test-slices https://dzone.com/articles/spring-boot-web-slice-test【讨论】:
是的,我认为 MVC 测试肯定不是集成测试,从技术上讲它更接近单元测试。以上是关于带有模拟的 MvcTest 是集成测试或单元测试的主要内容,如果未能解决你的问题,请参考以下文章