【问题标题】:JUnit 5 test with MockMvc not fetching data from database使用 MockMvc 的 JUnit 5 测试未从数据库中获取数据
【发布时间】: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


【解决方案1】:

在单元测试中从真实数据库中获取数据不被视为标准做法。 相反,您可以创建将'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。被测试的组件和它的直接后继者(这里是服务类)只需要存在。

【讨论】:

    【解决方案2】:

    检查您的测试是否使用其他数据库配置,在 test/resources/application.properties 文件或 .yml 文件中配置。

    可能您使用邮递员和使用测试方法访问的数据库实例不同。

    【讨论】:

      猜你喜欢
      • 2021-01-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-07-19
      • 2019-08-08
      • 2015-11-20
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多