Issue
I met this problem when I tried to execute some JUnit mockito tests.
To make it easy to understand my question, I will provide an example below:
Class A {
public String test(String para1) {
//...do whatever stuff
return para1;
}
}
Class B {
public void run() {
A a = new A();
String result = a.test("test");
System.out.println(result);
}
}
when(mockA.test(anyString()).thenReturn("mockResult");
A mockA = mock(A.class);
//Instead of doing mockA.test(), I do the following:
B b = new B();
b.run();
The question is, how can I replace the "a" object in B's run() method with the "mockA" object? This way I can start the code execution from b.run() and also utilize the mock object inside of the code execution process.
Any help would be greatly appreciated! :P
Solution
There are couple of options instead of creating new instance of A inside of run
:
Pass instance of A in the constructor, like
class B { private A a; B(A a) { this.a = a; } void run() { a.test("something"); } }
So your test code will change to
B b = new B(mockA); b.run();
Create setter method:
class B { private A a; void setA(A a) { this.a = a; } void run() { a.test("something"); } }
So your test code will change to
B b = new B(); b.setA(mockA); b.run();
Usually second method is preferred.
Answered By - artie
Answer Checked By - Clifford M. (JavaFixing Volunteer)