I am trying to create Junit test case using Mockito framework and junit5. I am working on the below code:
Class ClasstToBeTested {
FirstClass a = new FirstClass();
public String methodToBeTested() {
String str = a.firstMethod();
return str;
}
}
Class FirstClass {
SecondClass b = new SecondClass();
public String firstMethod() {
String str = b.secondMethod();
return str;
}
}
I have a class structure like above and I need to mock secondMethod.
I tried @spy on FirstClass and mocked SecondClass and secondMethod, but mocking didn't happen. How can I mock in this case?
Note - I am not in a position to change the structure of the class.
You have some options:
SecondClass
instance instead of building it inside FirstClass
: class FirstClass {
private final SecondClass b;
// Injecting the SecondClass instance
FistClass(SecondClass b) {
this.b = b;
}
public String firstMethod() {
String str = b.secondMethod();
return str;
}
}
Then you can just inject a mock in your test.
SecondClass
setter just for tests. class FirstClass {
SecondClass b = new SecondClass();
// Annotate with a visibility for test annotation if available.
// Here one can inject a mock too, but can cause problems if used inadvertently.
void setSecondClassForTests(SecondClass b) {
this.b = b;
}
public String firstMethod() {
String str = b.secondMethod();
return str;
}
}
Then you call the setter on the test and pass the mock.
final Field declaredField = instanceOfFirstClass.getClass().getDeclaredFields("b");
declaredField.setAccessible(true);
declaredField.set(instanceOfFirstClass, yourMockedInstance);
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.