模拟超类受保护方法为类变量上的 @Mock 返回 null
我正在尝试为最常见的场景编写单元测试。
class A{
protected void m1() {
//something
}
}
//class A is from a different/external binary
class B extends A {
@Autowired Properties props
public void m2() {
//something
if(props.getSomething()) {
m1();
}
}
}
class BTest {
@Mock Properties props;
@Test
public void testM2() {
MockB b = mock(MockB.class);
doNothing().when(b).m1();
when(b.m2()).thenCallRealMethod();
when(props.getSomething()).thenReturn(1);
}
class MockB extends B {
@Override
public void m1() {
return;
}
}
}
这里的问题是,到目前为止测试失败。当我尝试调试测试时,我发现 null 被注入到 props 中,这导致了 NPE。当我从测试中删除类实现时,我可以看到 props 模拟工作正常,但在 m1() 调用时失败。有人可以帮助我,我在这里缺少什么,我尝试使用 MockB b 引用来引用道具,例如 b.props 但这也引发了 NPE。非常感谢这里的任何帮助。
I am trying to write a unit test for a most common scenario.
class A{
protected void m1() {
//something
}
}
//class A is from a different/external binary
class B extends A {
@Autowired Properties props
public void m2() {
//something
if(props.getSomething()) {
m1();
}
}
}
class BTest {
@Mock Properties props;
@Test
public void testM2() {
MockB b = mock(MockB.class);
doNothing().when(b).m1();
when(b.m2()).thenCallRealMethod();
when(props.getSomething()).thenReturn(1);
}
class MockB extends B {
@Override
public void m1() {
return;
}
}
}
problem here is, as of now test is failing. When I tried debugging the test, I have observed null is being injected into props and this is causing NPE. When I remove class implementation from test, I can see props mock is working fine but it is failing at m1() call. Can someone please help me what I am missing here, I tried referring props with MockB b reference like b.props but this is also throwing NPE. Any help here is greatly appreciated.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我只使用了mockito,你不需要mock类,下面应该可以工作
如果你使用
super.m1()
这将不起作用I have used only mockito, You do not need the mock class, below should work
If you use
super.m1()
this won't work