How to override a method in unit tests that is called from which the class being tested
21,203
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();
}
}
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
}
}
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
Author by
Khawar Ali
-> Native iOS development -> Mobile game development using cocos2d and cocos2d-x -> Web technologies
Updated on May 15, 2020Comments
-
Khawar Ali almost 4 years
I am testing a class A's function func1.
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); } }
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; } }
But it is still calling the func2 in the class B. Please suggest how to handle this.
-
Khawar Ali almost 8 yearsI ended up solving this throw dependency injection, but this is great advise! Thanks!