如何在单元测试中重写被测试的类所调用的方法 [英] How to override a method in unit tests that is called from which the class being tested
问题描述
我正在测试A类的函数func1.
I am testing a class A's function func1.
Func1具有B类的局部变量,并调用B的函数func2.代码看起来像这样:
Func1 has a local variable of Class B and calls B's function func2. Code looks something like this:
public Class A
{
public func1()
{
B object = new B();
int x = object.func2(something);
}
}
当我在其单元测试中测试func1时,我不想调用func2.
When I am testing func1 in its unit tests, I don't want func2 to get called.
所以我正在尝试在测试中做类似的事情:
So I am trying to do something like this in the test:
B textObject = new B()
{
@override
int func2(something)
{
return 5;
}
}
但是它仍在类B中调用func2.请提出如何处理此问题的方法.
But it is still calling the func2 in the class B. Please suggest how to handle this.
推荐答案
如果要覆盖new B()
构造函数调用,请将其放在自己的方法中.
If you want to override the new B()
constructor call - place it in an own method.
public Class A
{
public func1()
{
B object = newB();
int x = object.func2(something);
}
protected B newB(){
return new B();
}
}
在测试中,您可以覆盖B
构造函数调用.
In your test you can then override the B
constructor call.
public class APartitialMock extends A {
protected B newB(){
return new BMock();
}
}
public class BMock extends B {
int func2(something) {
return 5
}
}
然后使用APartitialMock
与您的B
类型一起测试func1
.
Then use APartitialMock
to test the func1
with your kind of B
.
PS If you can or want to use a framework take a look at powermock - Mock Constructor
这篇关于如何在单元测试中重写被测试的类所调用的方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!