我正在尝试使用 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 文件中的调试屏幕截图:-
您能告诉我我在哪里犯了错误吗?
谢谢
最佳答案
@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/