AmI*_*Yet 5 java rest spring-boot
我有一个假设的休息终点。
@GetMapping(value = "/happy/{happyId}",
produces = MediaType.APPLICATION_JSON_VALUE)
public Response<?> getHappy(@PathVariable Long happyId) {
Response response = new Response();
response.update(happyService.getById(happyId));
return response;
}
Run Code Online (Sandbox Code Playgroud)
在此代码中,如果 id 不存在, happyService 可能会抛出 UnhappyException ,并且此代码在另一个地方进行了测试,例如HappyServiceTest。
现在,假设如果我想测试我的其余控制器,我是否也应该测试异常流?或者这是不必要的?
例如)
HappyRestControlerTest.java
@Test
void testUnHappy() {
...
assertThrows(UnhappyException.class () -> {happyService.getById(-1L)});
}
Is this unnecessary test since I tested the behaviour of happyService in HappyServiceTest?
Run Code Online (Sandbox Code Playgroud)
对于这一层应用程序,有一种特定类型的测试。这称为 MVC 测试,为此,您可以使用针对某些特定输入的特定响应来模拟您的服务,并通过测试验证控制器的行为是否符合预期。
请参阅以下示例
@SpringBootTest
@AutoConfigureMockMvc
public class TestingWebApplicationTest {
@Autowired
private MockMvc mockMvc;
@MockBean
private HappyService service;
@Test
public void shouldReturnMessage() throws Exception {
when(service.getById(1)).thenReturn("Happy Response 1");
this.mockMvc.perform(get("/happy/1"))
.andExpect(status().isOk())
.andExpect(content()
.string(containsString("Happy Response 1")));
}
}
Run Code Online (Sandbox Code Playgroud)
这是一种模拟测试,客户端将从控制器 http 状态代码、http 标头、http 正文内容等接收到什么内容...
Spring Boot 已通过依赖项包含对此 MockMvc 测试的支持
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
2872 次 |
最近记录: |