简体   繁体   中英

Spring Boot JUnit Service Mockito Null Pointer Exception

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());
    }
}

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

@ExtendWith(MockitoExtension.class)
public class CategoryServiceTest{

    @InjectMocks
    private CategoryService categoryService;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM