如何模拟正在测试的同一类中的另一个方法? [英] How to mock another method in the same class which is being tested?
问题描述
我正在为一个具有两个方法 methodA、methodB 的类编写 JUnit 测试用例.我想在我的测试用例中模拟从 methodA 对 methodB 的调用我在我正在测试的类上使用 spy,但仍然执行 methodB.
I am writing JUnit Test case for a class which has two methods methodA,methodB. I would like to mock the call to the methodB from methodA in my test case I am using spy on the class which I am testing, but still the methodB gets executed.
这里是课程
public class SomeClass
{
public Object methodA(Object object)
{
object=methodB(object);
return object;
}
public Object methodB(Object object)
{
//do somthing
return object;
}
}
这里是测试类
@RunWith( org.powermock.modules.junit4.legacy.PowerMockRunner.class )
@PrepareForTest(SomeClass.class)
public class SomeClassTest {
private SomeClass var = null;
@Before
public void setUp() {
var=new SomeClass();
}
@After
public void tearDown()
{
var= null;
}
@Test
public void testMethodA_1()
throws Exception {
Object object =new Object();
SomeClass spy_var=PowerMockito.spy(var);
PowerMockito.when(spy_var.methodB(object)).thenReturn(object);
Object result = var.methodA(object);
assertNotNull(result);
}
}
虽然我已经嘲笑了方法 B 仍然被调用请建议我一个解决方案,以正确的方式模拟来自同一类的 methodA 的 methodB 调用.
The method B still gets the called though I have mocked it PLease suggest me a solution with the proper way of mocking the methodB call from methodA of the same class.
推荐答案
我昨天遇到了这个,间谍最好这样做:
I ran into this yesterday, for spies is best to do:
doReturn(X).when(spy).method(any())
这篇关于如何模拟正在测试的同一类中的另一个方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!