junit5测试没有从数据库获取数据

xxb16uws  于 2021-07-13  发布在  Java
关注(0)|答案(2)|浏览(461)

当从postman发出请求时,返回数据,但是在junit5测试中,我的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());
  }
}
m3eecexj

m3eecexj1#

检查您的测试是否使用其他数据库配置(在test/resources/application.properties文件或.yml文件中配置)。
可能您不使用postman访问同一个数据库示例,而使用test方法访问同一个数据库示例。

gmol1639

gmol16392#

在单元测试中从真实数据库中获取数据不被认为是标准实践。相反,您可以创建mock对象,它将“模拟”或“模仿”真实数据库的行为。

@ExtendWith(SpringRunner.class)
class UserControllerTest {

  MockMvc mockMvc;

  @Mock
  private UserService userService;

  @InjectMocks
  private UserController userController;

  @BeforeEach
  void setUp() {            
    mockMvc = standaloneSetup(userController).build();
    User user = User.builder().your_field1(FIELD_VALUE).your_field2(FIELD_VALUE).build(); //Use the fields as per your code
  }

  @Test
  void getAllData() throws Exception {
    when(userService.getAllDataForUser(USER_ID)).thenReturn(user);  //Use the method name as per your code

    MvcResult result = mockMvc.perform(get("/getAllData"))
                            .andExpect(status().isOk())
                            .andReturn();

    System.out.println("My Result" + result.getResponse().getContentAsString());
  }
}

另外,由于您正在测试控制器,因此不需要存储库的模拟bean。被测试的组件及其直接的继承者(这里是服务类)只需要存在。

相关问题