CommencerCommencer gratuitement

Unit test: Database with a list

Consider the ErrorStore and InfoStore from the lesson, but now our process() method is accepting a list of messages. Given the input list provided, verify each database was called the correct number of times.

Cet exercice fait partie du cours

Introduction to Testing in Java

Afficher le cours

Instructions

  • Create a mock for the InfoStore.
  • Create a mock for the ErrorStore.
  • Verify how many times the InfoStore mock will be called with the current arguments.
  • Verify how many times the ErrorStore mock will be called with the current arguments.

Exercice interactif pratique

Essayez cet exercice en complétant cet exemple de code.

import org.junit.jupiter.api.Test;
import java.util.*;
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 MessageProcessorTest {
    @Test
    void process_savesToCorrectDatabase_whenValidInputList() {
        List sampleMessages = new ArrayList<>();
        sampleMessages.add("[INFO] An info message.");
        sampleMessages.add("[INFO] An info message.");
        sampleMessages.add("[ERROR] An error message.");
        sampleMessages.add("[INFO] An info message.");
        
    	// Create a mock for the InfoStore
        ____;
        // Create a mock for the ErrorStore
        ____;
        MessageProcessor processor = new MessageProcessor(infoStore, errorStore);
        processor.process(sampleMessages);

		// Verify how many times the infoStore has to store the message
        ____.save("[INFO] An info message.");
        // Verify how many times the errorStore has to store the message
        ____.save("[ERROR] An error message."); 
    }
}

public class MessageProcessor {
    private InfoStore infoStore; private ErrorStore errorStore;
    public MessageProcessor(InfoStore infoStore, ErrorStore errorStore) {
        this.infoStore = infoStore; this.errorStore = errorStore;
    }
    public void process(List messages) {
        for (String message : messages) {
            System.out.println("Processing message: " + message);
            if (message.startsWith("[INFO]")) infoStore.save(message);
            if (message.startsWith("[ERROR]")) errorStore.save(message);
        }
    }
}

interface InfoStore { void save(String message); }
interface ErrorStore { void save(String message); }
Modifier et exécuter le code