Unit test: Database message
Consider the ErrorStore
and InfoStore
from the lesson. Suppose the process(String message)
method is used on a [WARN]
message, which means it would end up in neither database. Write a test to verify that.
This exercise is part of the course
Introduction to Testing in Java
Exercise instructions
- Verify the message did not end up in
infoStore
. - Verify it also did not end up in
errorStore
using thetimes()
verify approach. - In that same statement, add the database method,
save()
, that wasn't called.
Hands-on interactive exercise
Have a go at this exercise by completing this sample code.
import org.junit.jupiter.api.Test;
import java.util.List;
import static com.datacamp.util.testing.CustomJUnitTestLauncher.launchMockitoTestsAndPrint;
import static org.mockito.Mockito.*;
public class Main {
public static void main(String[] args) {
launchMockitoTestsAndPrint(MessageProcessorTest.class);
}
}
class MessageProcessor {
private InfoStore infoStore;
private ErrorStore errorStore;
public MessageProcessor(InfoStore infoStore, ErrorStore errorStore) {
this.infoStore = infoStore;
this.errorStore = errorStore;
}
public void process(String message) {
if (message.startsWith("[INFO]")) infoStore.save(message);
if (message.startsWith("[ERROR]")) errorStore.save(message);
}
}
class MessageProcessorTest {
@Test
void process_savesNowhere_whenWrongMessageType() {
InfoStore infoStore = mock(InfoStore.class);
ErrorStore errorStore = mock(ErrorStore.class);
MessageProcessor processor = new MessageProcessor(infoStore, errorStore);
String message = "[WARN] The search is slow.";
processor.process(message);
// Verify infoStore was not called
____(infoStore);
// Verify errorStore.save was called 0 times
verify(errorStore, ____).____(message);
}
}
interface InfoStore {
void save(String message);
}
interface ErrorStore {
void save(String message);
}