【问题标题】:CrudRepository test cases without inserting data in DBCrudRepository 测试用例,无需在数据库中插入数据
【发布时间】:2019-05-12 02:34:27
【问题描述】:

我有一个实现 CrudRepository 的存储库类。然后在服务类中,我自动连接了这个存储库。然后在控制器类中,我自动装配了这个服务。

我想写控制器类的测试用例。我正在使用以下配置。

    @RunWith(SpringJUnit4ClassRunner.class)
    @SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT)
    public class XYZControllerTest {

        MockMvc mockMvc;

        @Mock
        private XYZController xyzController;

        @Autowired
        private TestRestTemplate template;

        @Autowired
        XYZRepository xyzRepository;

        @Before
        public void setup() throws Exception {
            mockMvc = MockMvcBuilders.standaloneSetup(xyzController).build();
        }

        @Test
        public void testPanelShouldBeRegistered() throws Exception {
            HttpEntity<Object> xyz = getHttpEntity("{\"name\": \"test 1\", \"email\": \"test10000000000001@gmail.com\","
                    + " \"registrationNumber\": \"41DCT\",\"registrationDate\":\"2018-08-08T12:12:12\" }");
            ResponseEntity<XYZ> response = template.postForEntity("/api/xyz", xyz, XYZ.class);

    }
}

我的问题是,当我运行测试用例时,数据将插入用于应用程序的数据库中。我可以在不向数据库中插入数据的情况下对其进行测试吗?

【问题讨论】:

  • 没有。它不一样。在那个问题中,他们建议进行集成测试。
  • 你必须模拟 XYZRepository 而不是从 Spring 配置中连接它。

标签: spring-boot junit mockito


【解决方案1】:

从概念上讲,当我们测试服务时,我们模拟存储库而不是注入。

您需要模拟您的存储库并设置返回数据的行为。

一个例子:

@MockBean
XYZRepository xyzRepository;

@Test
public void test() {

    // other mocks
    //
    when(xyzRepository.findAll()).thenReturn(Arrays.asList(new XYZ()));

    // service calls
    // assertions
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-05-04
    • 2013-01-08
    • 2021-07-04
    • 2019-07-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-12-21
    相关资源
    最近更新 更多