java - Junit 在 EntityManager 上抛出 NullPointerException
问题描述
我正在运行抛出的Junit Test
案例NullPointerException
这是我的 Junit 测试类结构
@RunWith(SpringJUnit4ClassRunner.class)
public class EmployeeTest {
@InjectMocks
EmployeeRepository empRepo;
@InjectMocks
EmployeeService empService;
@Mock
EntityManager entityManager;
List<Employee> empList=new ArrayList<Employee>();
@Before
public void setUp() throws Exception {
MockitoAnnotations.initMocks(this);
}
@Test
public void getEmployyeList(){
Employee e = new Employee(111,'Raunak','kumar','Hero Inc');
List<Employee> empList=empService.getAllEmployee();
Employee e1 = empList.stream().filter(emp->emp.getEmpId()==111).findAny().get();
assertEquals(e,e1);
}
}
我EmployeeService
正在使用的EntityManager
看起来像
public class EmployeeService{
@Autowired
EntityManager em;
public List<Employee> getAllEmployee(){
return em.createNativeQuery("select e.* from employee e").getResultList();
}
}
当我debugging
找到em.createNativeQuery("select e.* from employee e")
返回null的代码时。从Rest API
它的工作正常。
试过
when(empRepo.findAll()).thenReturn(empList);
assertThat(users, containsInAnyOrder(
hasProperty("lastName", is("Kumar"))
));
但empRepo.findAll()
也返回[]
解决方案
您必须使用 mockito 的 when 和 thenReturn 在您的测试用例(getEmployyeList)中存根模拟实体管理器,如下所示,这应该解决 NPE
@Test
public void getEmployyeList(){
Employee e = new Employee(111,'Raunak','kumar','Hero Inc');
Query query = mock(Query.class);
when(entityManager.createNativeQuery(anyString())).thenReturn(query);
doReturn(Arrays.asList(e)).when(query).getResultList();
List<Employee> empList=empService.getAllEmployee();
Employee e1 = empList.stream().filter(emp->emp.getEmpId()==111).findAny().get();
assertEquals(e,e1);
}
推荐阅读
- r - r代码中带有轮廓图的错误代码
- javascript - Google 地方信息覆盖自动完成关闭
- python - 从 XML 标记创建原始文本
- ios - 当所有视图都与等宽约束对齐时,如何隐藏一些视图?
- excel - VBA 函数返回 0
- javascript - Google App Script - Web App - 获取活动工作表名称
- javascript - 在 HTMLUnit 中获取动态注入内容的问题
- powershell - PowerShell Active Directory lastLogon/lastLogonTimestamp -- 带有填充 lastLogonTimestamps 的空 lastLogon
- python - 在 matplotlib 中自动缩写长度字符串
- c# - 如何在模拟 FromSql() 方法时克服 IQueryable 不实现 IAsyncQueryProvider?