【发布时间】:2021-07-09 19:26:01
【问题描述】:
当从 Postman 发出请求时,会返回数据,但在 JUnit 5 测试的情况下,我的 API 返回一个空列表。
如何让我的测试访问我的真实数据库并返回数据?
@ExtendWith(SpringExtension.class)
@WebMvcTest(UserController.class)
class UserControllerTest {
@Autowired
MockMvc mockMvc;
@Autowired
WebApplicationContext webApplicationContext;
@MockBean
private UserService userService;
@MockBean
private UserRepository userRepository;
@BeforeEach
void setUp() {
mockMvc = webAppContextSetup(webApplicationContext).build();
}
@Test
void getAllData() throws Exception {
MvcResult result = mockMvc.perform(get("/getAllData"))
.andExpect(status().isOk())
.andReturn();
System.out.println("My Result" + result.getResponse().getContentAsString());
}
}
【问题讨论】:
-
您使用模拟服务和模拟存储库。这永远不会命中数据库。如果要创建集成测试,请删除 mock 并使用将 webmvctest 更改为 springboottest
标签: spring spring-boot spring-mvc junit