Given: Java 8
Mockito 4.3
Junit 4.11
Here my java code:
public interface ClientListener {
void addClientStatusListener(StatusListener statusListener);
}
@FunctionalInterface
public interface StatusListener {
void statusChange(ClientStatus clientStatus);
}
public class MyIoClientBuilder {
public MyIoClientBuilder subscribeProcessed(MyInterface myInterface) {
// Some logic here
return this;
}
public MyIoClientBuilder build() {
// some logic
return this;
}
}
public interface MyInterface {
public void myInnerMethod(String arg);
}
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
public class MyIoClient {
public MyIoClient(ClientListener clientListener) {
clientListener.addClientStatusListener(new StatusListener() {
@Override
public void statusChange(ClientStatus clientStatus) {
if (clientStatus.equals(ClientStatus.AUTHORIZED)) {
new MyIoClientBuilder()
.subscribeProcessed(new MyInterface() {
@Override
public void myInnerMethod(String jsonString) {
try {
Person person = new ObjectMapper().readValue(jsonString, Person.class);
System.out.println("person = " + person);
} catch (JsonProcessingException e) {
throw new RuntimeException(e);
}
}
}).build();
}
}
});
}
}
I need to validate that if jsonString is invalid json then throw RuntimeException.
Here my unit test:
import org.junit.Test;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import static org.mockito.Mockito.*;
@Test
public void shouldThrowRuntimeExceptionWhenJsonInvalid() {
// Arrange
ClientListener clientListenerSpy = spy(ClientListener.class);
doAnswer(
invocation -> {
StatusListener clientStatusListener = invocation.getArgument(0);
clientStatusListener.statusChange(ClientStatus.AUTHORIZED);
return null; // Void methods must return null in doAnswer()
})
.when(clientListenerSpy)
.addClientStatusListener(any(StatusListener.class));
// Assert
assertThatThrownBy(() -> {
new MyIoClient(clientListenerSpy);
}).isInstanceOf(RuntimeException.class);
}
As result in class MyIoClient successfully call method statusChange.
OK.
But the method myInnerMethod does not call in anonymous inner class MyEmiter.
As result here error:
java.lang.AssertionError:
Expecting code to raise a throwable.
subscribeProcessed? When is itsmyInnerMethodcalled (by your production code)?