【问题标题】:How to write junit test cases for rest controller, service and dao layer using springboot?如何使用springboot编写rest控制器、服务和dao层的junit测试用例?
【发布时间】:2019-12-30 21:17:59
【问题描述】:

JUnitRestController、Service和DAO层的测试用例怎么写?

我试过MockMvc

@RunWith(SpringRunner.class)
public class EmployeeControllerTest {

    private MockMvc mockMvc;

    private static List<Employee> employeeList;

    @InjectMocks
    EmployeeController employeeController;

    @Mock
    EmployeeRepository employeeRepository;

    @Test
    public void testGetAllEmployees() throws Exception {

        Mockito.when(employeeRepository.findAll()).thenReturn(employeeList);
        assertNotNull(employeeController.getAllEmployees());
        mockMvc.perform(MockMvcRequestBuilders.get("/api/v1/employees"))
                .andExpect(MockMvcResultMatchers.status().isOk());
    }

如何验证 REST 控制器和其他层中的 CRUD 方法?

【问题讨论】:

  • 你可能会询问它的主体作为响应,以检查它是否保存在数据库中。
  • 好的,你知道如何使用 JUnit 和 Mockito 模拟 DAOlayer 和服务层吗?
  • 在更真实的环境中,您可以使用@RunWith(SpringRunner.class) 在应用程序运行时测试您的服务,并使用@DataJpaTest 来检查是否保存了某个实体或其他什么。
  • 谢谢,您还知道用于 DAO 层测试的 DBUnit 吗?
  • 是的,你也可以使用它,但是查看你的代码,看起来你没有使用 DAO 对象。

标签: java rest spring-boot junit mockito


【解决方案1】:

您可以使用@RunWith(MockitoJUnitRunner.class) 进行单元测试,并使用您的服务层 模拟您的DAO 层 组件。你不需要SpringRunner.class。

Complete source code

    @RunWith(MockitoJUnitRunner.class)
    public class GatewayServiceImplTest {

        @Mock
        private GatewayRepository gatewayRepository;

        @InjectMocks
        private GatewayServiceImpl gatewayService;

        @Test
        public void create() {
            val gateway = GatewayFactory.create(10);
            when(gatewayRepository.save(gateway)).thenReturn(gateway);
            gatewayService.create(gateway);
        }
    }

您可以使用@DataJpaTest 进行集成测试 你的DAO 层

    @RunWith(SpringRunner.class)
    @DataJpaTest
    public class GatewayRepositoryIntegrationTest {

        @Autowired
        private TestEntityManager entityManager;

        @Autowired
        private GatewayRepository gatewayRepository;

        // write test cases here     
    }

查看article 了解更多关于使用 Spring Boot

进行测试的详细信息

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-01-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-12-01
    相关资源
    最近更新 更多