如何使用 Mockito 正确测试 Spring Boot [英] How to properly test a Spring Boot using Mockito
问题描述
我从未做过测试,而是决定做我的第一次测试.我使用的是 Spring Boot,默认布局如下:https://zapodaj.net/c8b65f1644e95.png.html启动时创建的文件是这样的
I never did a test and decided I would do my first. I am using Spring Boot and by default the layout is as follows: https://zapodaj.net/c8b65f1644e95.png.html The file that is created on startup looks like this
@RunWith(SpringRunner.class)
@SpringBootTest
public class RestWebServicesApplicationTests {
@Test
public void contextLoads() {
}
}
这里我不做任何更改,因为我不需要它.相比之下,我创建了一个新类
I do not change anything here, because I do not need it. By contrast, I created a new class
public class CheckUserDataRestControllerTest {
@Mock
private UserService userService;
@InjectMocks
private CheckUserDataRestController checkUserDataRestController;
private MockMvc mockMvc;
@Before
public void setup() {
MockitoAnnotations.initMocks(this);
mockMvc = MockMvcBuilders.standaloneSetup(checkUserDataRestController).build();
}
@Test
public void textExistsUsername() throws Exception {
mockMvc
.perform(get("/checkUsernameAtRegistering")
.param("username", "jonki97"))
.andExpect(status().isOk());
}
}
测试控制器方法,应该返回状态OK.
To test the controller method, which should return the status OK.
@GetMapping("/checkUsernameAtRegistering")
public HttpEntity<Boolean> checkUsernameAtRegistering(@RequestParam String username) {
return ResponseEntity.ok().body(!userService.existsByUsername(username));
}
但是,在考试的时候,他把我扔了
However, during the test, he throws me out
java.lang.AssertionError: Status
Expected :200
Actual :404
<Click to see difference>
at org.springframework.test.util.AssertionErrors.fail(AssertionErrors.java:54)
...
这是经过测试的控制器:https://pastebin.com/MWW9YwiH
This is the tested controller: https://pastebin.com/MWW9YwiH
我没有做任何特殊的配置,因为我没有发现我需要做些什么.
I did not make any special configurations because I did not find out that I needed to do something.
推荐答案
错误 404 表示 Mock 无法识别要测试的端点.终点应该是:
The error 404 means the Mock does not recognize your endpoint to test. The end point should be:
@Test
public void textExistsUsername() throws Exception {
mockMvc
.perform(get("/checkUserData/checkUsernameAtRegistering")
.param("username", "jonki97"))
.andExpect(status().isOk());
}
希望对您有所帮助.
这篇关于如何使用 Mockito 正确测试 Spring Boot的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!