java - 带有 H2 数据库的 JUnit Mockito

标签 java spring junit

我正在尝试使用 Mockito 框架为 Spring Boot Controller 编写 JUnit。我已经注入(inject)了服务类。我正在使用嵌入式 h2 数据库。

当我尝试调试编写的测试用例时,我可以看到它没有调用服务方法的实现类并返回空数组。我已附上 Controller 类的调试屏幕截图。

下面是编写的JUnit类文件:-

package com.testSpringBoot;

import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;

import java.util.ArrayList;
import java.util.List;

import org.junit.Before;
import org.junit.Ignore;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.Mockito;
import org.mockito.MockitoAnnotations;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.request.MockMvcRequestBuilders;
import org.springframework.test.web.servlet.setup.MockMvcBuilders;

import com.testSpringBoot.controller.EmployeeController;
import com.testSpringBoot.dto.EmployeeDTO;
import com.testSpringBoot.repository.EmployeeRepository;
import com.testSpringBoot.service.EmployeeService;

import junit.framework.Assert;

@RunWith(SpringRunner.class)
@SpringBootTest
public class EmployeeControllerJUnit {

    private MockMvc mockMvc;

    @Mock
    private EmployeeService employeeService;

    @InjectMocks
    private EmployeeController employeeController;

    @Before
    public void setup() {
        MockitoAnnotations.initMocks(this);

        mockMvc = MockMvcBuilders.standaloneSetup(employeeController).build();
    }

    @Test
    public void employeeControllerTest() throws Exception {
        Mockito.when(employeeService.getAllEmployees()).thenReturn(new ArrayList<EmployeeDTO>());

        mockMvc.perform(MockMvcRequestBuilders.get("/employee/getAllEmployees"))
        .andExpect(status().isOk());
    }   
}

Controller 文件中的调试屏幕截图:-

Debug screenshot

您能告诉我我在哪里犯了错误吗?

谢谢

最佳答案

@Mock
private EmployeeService employeeService;

这指示 Mockito JUnit 运行程序创建 EmployeeService 类型的模拟。模拟不使用您可以在 EmployeeService 类中编写的任何实现(如果 EmployeeService 是接口(interface),则在其任何实现中)。相反,它只是“ mock ”该类的行为。

在这里,您指示模拟在调用其 getAllEmployees() 方法时返回一个空列表:

Mockito.when(employeeService.getAllEmployees()).thenReturn(new ArrayList<EmployeeDTO>());

根据您的描述,它就是这样做的。

您需要决定是否需要 mock 您的服务。如果没有,请不要使用 Mockito 的模拟,而只使用您的服务实现(尽管这会将您的测试转换为集成测试)。

关于java - 带有 H2 数据库的 JUnit Mockito,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48527794/

相关文章:

java - Mockito 因使用无效参数名称异常启用的内联模拟而失败

java - JMockit - 意外调用

java - 在java中将一个列表转换为另一个列表

java - Thymeleaf @Valid LazyInitializationException

java - 推土机给我异常(exception)

java - Spring 数据库负载测试 : How to release connections

java - Junit 零测试

java - 如何使用 JSON 按声明顺序序列化带有枚举键的映射?

java - 如何在 Android 中一次又一次地从 wifi 列表中选择相同的 wifi 运营商?

java - Java 中的 __LINE__ 等效项?