I am pretty new to Mockito and Spring. I am trying to mock many methods of many classes. I want to create a functionality where bean name and method name can given as input as string, and it will throw same exception.
Example I have a class A and Class B
@Named
public Class A {
public void methodInA() {
System.out.println("In A");
}
}
@Named
public Class B {
public void methodInB() {
System.out.println("In B");
}
}
Below is what I am trying to do in test.
TestConfig:
@SpyBean
A a;
Test::
String className = "A";
String methodName = "methodInA";
Object bean = applicationContext.getBean("a");
Class clazzToSpy = bean.getClass();
Class[] paramTypes = clazzToSpy.getMethod(methodName);
Answer answer = new Answer() {
@Override
public Object answer(final InvocationOnMock invocationOnMock) throws Throwable {
if(invocationOnMock.getMethod().getName().equals(methodName)) {
throw new UnknownError("Manual Exception Created");
}
return invocationOnMock.callRealMethod();
}
};
//Here I want to use the answer on the mock Something like below.
Method mockedMethod = clazzToSpy.getMethod(methodName, paramTypes);
Mockito.doAnswer(answer).when(mockedMethod)
I understand there is a gap in my understanding. How do I achieve something like above?
Has someone tried doing similar thing?
Related threads which I have tried: