Home > Blockchain >  Spring Boot JUnit Service Mockito Null Pointer Exception
Spring Boot JUnit Service Mockito Null Pointer Exception

Time:10-09

I have a problem about writing a JUnit Service with Mockito in Spring Boot example.

I got null pointer exception for result as it has null.

How can I fix that issue?

Here are the code snippets shown below.

Here is the service class of Category

@Service
@RequiredArgsConstructor
public class CategoryService {

    private final CategoryRepository categoryRepository;


    public Category findCategory(Long id) {
        return categoryRepository.findById(id).orElseThrow();
    }

    public Category findByName(String value) {
        return categoryRepository.findByName(value).orElseThrow();
    }
}

Here is the JUnit Service class shown below

@ExtendWith(MockitoExtension.class)
public class CategoryServiceTest{

    @Mock
    private CategoryService categoryService;

    @Mock
    private CategoryRepository categoryRepository;

    @Test
    void givenCategory_whenLoadCategory_thenReturnCategory() {

        // given - precondition or setup
        Category category = Category.builder().name("Category 1").build();

        // when -  action or the behaviour that we are going test
        when(categoryRepository.findById(anyLong())).thenReturn(Optional.of(category));

        Category result = categoryService.findCategory(anyLong());  // return null

        // then - verify the output
        assertEquals(category.getName(), result.getName());

    }

    @Test
    void givenCategory_whenFindByName_thenReturnCategory() {

        Category category = Category.builder().name("Category 1").build();

        // when -  action or the behaviour that we are going test
        when(categoryRepository.findByName("Category 1")).thenReturn(Optional.of(category));

        Category result  = categoryService.findByName("Category 1"); // return null

        // then - verify the output
        assertEquals(category.getName(), result.getName());
    }
}

CodePudding user response:

You're mocking the class under test, it should be

@ExtendWith(MockitoExtension.class)
public class CategoryServiceTest{

    @InjectMocks
    private CategoryService categoryService;
  • Related