I am trying to stub the following class:
public class MyFactory {
...
public Publisher getPublisher(String arg1, String arg2, Class<? extends QueueMessage> msgClass) {
do the magic...
}
}
I'd like to have two stubs in my test for two kinds of messages. Here is the stubbing code:
@Mock
private Factory factory;
@Mock
protected ThisMessagePublisher<ThisMessageType> thisMessagePublisher;
@Mock
protected ThatMessagePublisher<ThatMessageType> thatMessagePublisher;
when(factory.getPublisher(anyString(), anyString(), isA(ThisMessageType.class.getClass()))).thenReturn(thisMessagePublisher);
when(factory.getPublisher(anyString(), anyString(), isA(ThatMessageType.class.getClass()))).thenReturn(thatMessagePublisher);
It compiles correctly.
I then try to invoke the factory and the two publishers, hoping to verify one call for each publisher.
Publisher thisPublisher = factory.getPublisher("arg1", "arg2", ThisMessageType.class);
thisPublisher.publish(new ThisMessageType("Message"));
Publisher thatPublisher = factory.getPublisher("arg1", "arg2", ThatMessageType.class);
thatPublisher.publish(new ThatMessageType("Message"));
verify(thisPublisher).publish(Matchers.<ThisMessageType>any());
verify(thatPublisher).publish(Matchers.<ThatMessageType>any());
The test fails with the following error:
Wanted but not invoked:
thisPublisher.publish(
<any>
);
-> at ...
Actually, there were zero interactions with this mock.
Clearly, the second stubing is overriding the first one.
Diving into the isA() code and debugging shows that the inner generics are lost in the process of stubbing/calling/compiling. Scratching the back of my brain I seem to recall something about Java not being able to deal with inner generics like that.
So I tried stubbing the factory with argThat(), as follows, but the result is the same error as above.
when(Factory.getPublisher(anyString(), anyString(), argThat(new CustomTypeSafeMatcher<Class<ThisMessageType>>("Is class of ThisMessageType") {
@Override
protected boolean matchesSafely(Class<ThisMessageType> aClass) {
return aClass != null;
}
}))).thenReturn(thisPublisher);
when(Factory.getPublisher(anyString(), anyString(), argThat(new CustomTypeSafeMatcher<Class<ThatMessageType>>("Is class of ThatMessageType") {
@Override
protected boolean matchesSafely(Class<ThatMessageType> aClass) {
return aClass != null;
}
}))).thenReturn(thatPublisher);
Is there any way to achieve the stubbing and verification I'm aiming for. If so, how can it be done?
Aucun commentaire:
Enregistrer un commentaire