Sobes.tech
Senior

Write JUnit tests for RecommenderServiceImpl that cover the main functionality

sobes.tech AI

Answer from AI

To write JUnit tests for the RecommenderServiceImpl class, you need to cover the main scenarios of the service: obtaining recommendations, error handling, working with empty data, etc. Suppose the service depends on some repository or external API, then these dependencies should be mocked.

Example of a test using JUnit 5 and Mockito:

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

import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.MockitoAnnotations;

class RecommenderServiceImplTest {

    @Mock
    private RecommendationRepository recommendationRepository;

    @InjectMocks
    private RecommenderServiceImpl recommenderService;

    @BeforeEach
    void setUp() {
        MockitoAnnotations.openMocks(this);
    }

    @Test
    void testGetRecommendations_ReturnsList() {
        // Prepare data
        List<String> mockRecommendations = List.of("item1", "item2");
        when(recommendationRepository.findRecommendations(anyString())).thenReturn(mockRecommendations);

        // Call the method under test
        List<String> result = recommenderService.getRecommendations("user123");

        // Verify the result
        assertNotNull(result);
        assertEquals(2, result.size());
        assertEquals("item1", result.get(0));
    }

    @Test
    void testGetRecommendations_EmptyList() {
        when(recommendationRepository.findRecommendations(anyString())).thenReturn(Collections.emptyList());

        List<String> result = recommenderService.getRecommendations("user123");

        assertNotNull(result);
        assertTrue(result.isEmpty());
    }

    @Test
    void testGetRecommendations_RepositoryThrowsException() {
        when(recommendationRepository.findRecommendations(anyString())).thenThrow(new RuntimeException("DB error"));

        assertThrows(RuntimeException.class, () -> {
            recommenderService.getRecommendations("user123");
        });
    }
}

In this example:

  • Mockito is used to mock dependencies.
  • Normal operation, empty result, and exception handling are tested.
  • Tests for boundary cases and other service methods can be added.