模拟对象返回NPE

发布于 01-18 17:50 字数 617 浏览 1 评论 0原文

@SpringBootTest
@RunWith(MockitoJUnitRunner.class)
public class EmpCompSTest {
    @Mock
    private CompCl compCl; 

    @Test
    public void testGetEmpCompS() {
        EmpRequest request = new EmpRequest();
        Map<Long, List<CompCl.CompeSc>> comp = new HashMap<>();
        CompCl.CompSc compSc1
                = new CompCl.CompSc(); 
        comp.put(1L, Arrays.asList(compSc1));
     when(compCl.getUsrSc(request.getComp().keySet())).thenReturn(comp); 
    }
}

调试时,when() 所在行弹出 NullPointerException,且类 compCLnull

@SpringBootTest
@RunWith(MockitoJUnitRunner.class)
public class EmpCompSTest {
    @Mock
    private CompCl compCl; 

    @Test
    public void testGetEmpCompS() {
        EmpRequest request = new EmpRequest();
        Map<Long, List<CompCl.CompeSc>> comp = new HashMap<>();
        CompCl.CompSc compSc1
                = new CompCl.CompSc(); 
        comp.put(1L, Arrays.asList(compSc1));
     when(compCl.getUsrSc(request.getComp().keySet())).thenReturn(comp); 
    }
}

When debugging, an NullPointerException pops up on the line with when() and the class compCL is null.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

时间你老了2025-01-25 17:50:25

这是Junit5(木星)吗?在这种情况下,请使用 @ExtendWith(MockitoExtension.class) 而不是 @RunWith(MockitoJUnitRunner.class)

Is this Junit5 (Jupiter)? In that case use @ExtendWith(MockitoExtension.class) instead of @RunWith(MockitoJUnitRunner.class).

水波映月2025-01-25 17:50:25

应该为 EmpRequest 设置 Comp

Should have been set Comp for EmpRequest.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文