I'm having trouble with Mockito because I can't mock a property of a third class when I'm testing another one.
The class I'm testing:
@Component
public class MyTransformer {
@Autowired
private MyService myService;
public Output myMethod(Context context, Input input, Something something) throws Exception {
ServiceInput serviceInput = createServiceInput(something);
myService.doSomething(context, input, serviceInput);
return new Output();
}
}
The interface used in the previous class:
public interface MyService {
public void doSomething(Context context, Input input, Something something) throws Exception;
}
The real implementation of the service:
@Service
public class MyServiceImpl implements MyService {
@CustomServiceAnnotation(serviceName = "MyServiceName", apiPaths = {
ServiceApiPath.class
})
private GatewayProxyInvoker gatewayProxyInvoker; // this property is null
@Override
public void doSomething(Context context, Input input, Something something) throws Exception {
Request request = MyServiceCommand.createRequest(context, input, something);
Response response = Invoker.invoke(Response.class, gatewayProxyInvoker, context, request);
}
}
The class that throws a NullPointerException because the gatewayProxyInvoker property is null:
public class Invoker {
public static T invoke(final Class<T> responseType, final GatewayProxyInvoker gatewayProxyInvoker, final Context context, S request) throws Exception {
return gatewayProxyInvoker.invoke(responseType, context, request);
}
}
Test class:
@RunWith(MockitoJUnitRunner.class)
public class MyTransformerTest {
@InjectMocks
private MyTransformer transformer;
@Mock
private MyServiceImpl myService;
@Mock
private GatewayProxyInvoker gatewayProxyInvoker;
@Test
public void myMethodTest() throws Exception {
Response myResponse = new Response();
doCallRealMethod().when(myService).doSomething(any(Context.class), any(Input.class), any(Something.class));
when(gatewayProxyInvoker.invoke(any(Class.class), any(Context.class), any(Request.class))).thenReturn(myResponse);
transformer.myMethod(/*valid input params*/);
}
}
The property "gatewayProxyInvoker" is null so I'm thinking I'm doing something wrong in the process of mocking it.
The code works fine, it's my JUnit test that is not working.
How can I mock a property of a third class when I'm testing another one? In my example as you can see the method is void, the class I'm testing use an interface.
Thank you all, guys!