mocking超类保护方法在类变量上为@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被注入到道具中,这导致了NPE。当我从测试中移除类实现时,我可以看到props-mock运行良好,但在m1((调用时失败了。有人能帮帮我吗?我试着用MockB引用道具,比如b.props,但这也是投掷NPE。非常感谢在这里提供的任何帮助。

我只使用了mockito,您不需要mock类,下面应该可以使用

class BTest {
@Mock
private Prop props;

@Test
public void testM2() {
B bSpy = spy(new B(props));
when(props.getSomething()).thenReturn(1);
doNothing().when((A) bSpy).m1();
doCallRealMethod().when(bSpy).m2();

bSpy.m2();
}
}

如果你使用super.m1(),这将不起作用

最新更新