【发布时间】:2021-08-30 14:16:00
【问题描述】:
所以我的代码看起来像这样
class One
{
private final Two two;
public One()
{
two = new Two(this)
}
public void method1()
{
//do something
method2();
}
public void method2()
{
//do something
two.method3();
}
}
class Two
{
private final One one;
public Two(One one)
{
this.one=one;
}
public void method3()
{
//print something
}
}
现在,我想在第二类中模拟 method3(),而我测试第一类的 method1(),我的 Junit 是这样的。
private One one;
private Two two;
@Before
public void setup()
{
one = Mockito.spy(new One());
two = Mockito.spy(new Two(one));
}
@Test
pubic void testMethod1InClassOne()
{
Mockito.doNothing().when(testTwo).method3();
testOne.method1();
}
但不知何故,method3() 并没有被嘲笑,我仍然看到它的打印内容。但是,我可以成功地模拟 method2()。可能是因为 method2() 是直接从我正在测试的方法 method1() 调用的?请建议我如何模拟方法3。
谢谢, 梅赫
【问题讨论】:
标签: java unit-testing junit mocking mockito