Sobes.tech
Senior

Write tests for the notification filtering system using JUnit 5 and Mockito, covering main scenarios: null/empty input, valid notification, sender blocking, channel filtering, deduplication.

sobes.tech AI

Answer from AI

Below is an example of tests for a notification filtering system using JUnit 5 and Mockito, covering main scenarios:

import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.mockito.Mockito;
import static org.junit.jupiter.api.Assertions.*;
import static org.mockito.Mockito.*;

class NotificationFilterTest {

    private NotificationFilter filter;
    private SenderBlocklistService blocklistService;
    private DeduplicationService dedupService;

    @BeforeEach
    void setUp() {
        blocklistService = mock(SenderBlocklistService.class);
        dedupService = mock(DeduplicationService.class);
        filter = new NotificationFilter(blocklistService, dedupService);
    }

    @Test
    void testNullInput() {
        assertThrows(IllegalArgumentException.class, () -> filter.filter(null));
    }

    @Test
    void testEmptyInput() {
        Notification emptyNotification = new Notification("");
        assertFalse(filter.filter(emptyNotification));
    }

    @Test
    void testValidNotification() {
        Notification notification = new Notification("valid message");
        when(blocklistService.isBlocked(anyString())).thenReturn(false);
        when(dedupService.isDuplicate(any())).thenReturn(false);

        boolean result = filter.filter(notification);
        assertTrue(result);
    }

    @Test
    void testBlockedSender() {
        Notification notification = new Notification("message from blocked sender");
        when(blocklistService.isBlocked(anyString())).thenReturn(true);

        boolean result = filter.filter(notification);
        assertFalse(result);
    }

    @Test
    void testFilterByChannel() {
        Notification notification = new Notification("message");
        notification.setChannel("email");
        filter.setAllowedChannels(Set.of("sms", "push"));

        boolean result = filter.filter(notification);
        assertFalse(result);
    }

    @Test
    void testDeduplication() {
        Notification notification = new Notification("duplicate message");
        when(blocklistService.isBlocked(anyString())).thenReturn(false);
        when(dedupService.isDuplicate(notification)).thenReturn(true);

        boolean result = filter.filter(notification);
        assertFalse(result);
    }
}

In this example:

  • NotificationFilter is the notification filtering class.
  • SenderBlocklistService is the service for checking blocked senders.
  • DeduplicationService is the service for deduplicating notifications.

The tests cover:

  • null and empty input,
  • valid notification,
  • sender blocking,
  • channel filtering,
  • deduplication.