Home > Software engineering >  NullPointerException when running Service Test with Mockito
NullPointerException when running Service Test with Mockito

Time:12-27

This is my test class in which I created MockBean and I injected it into service object:

@ExtendWith(MockitoExtension.class)
@ExtendWith(SpringExtension.class)
public class CategoryServiceTest {

    @MockBean
    private CategoryRepository categoryRepository;

    @InjectMocks
    private CategoryServiceImpl categoryService;


    @Test
    public void testCheckUniqueInNewModeReturnDuplicateName() {
        Long categoryId = null;
        String name = "Computers";
        String alias = "abc";

        Category category = new Category(categoryId, name, alias);

        Mockito.when(categoryRepository.findByName(name)).thenReturn(category);

        String result = categoryService.checkUnique(categoryId, name, alias);

        assertThat(result).isEqualTo("DuplicateName");
    }
}

When I try to run this test, NullPointerException occurs:

java.lang.NullPointerException: Cannot invoke "com.marketcruiser.admin.category.CategoryRepository.findByName(String)" because "this.categoryRepository" is null

    at com.marketcruiser.admin.category.CategoryServiceImpl.checkUnique(CategoryServiceImpl.java:136)

This is my service class with the method checkUnique:

@Service
public class CategoryServiceImpl implements CategoryService{

    private final CategoryRepository categoryRepository;


    @Autowired
    public CategoryServiceImpl(CategoryRepository categoryRepository) {
        this.categoryRepository = categoryRepository;
    }

    @Override
    public String checkUnique(Long categoryId, String name, String alias) {
        boolean isCreatingNew = (categoryId == null || categoryId == 0);

        Category categoryByName = categoryRepository.findByName(name);

        if (isCreatingNew) {
            if (categoryByName != null) {
                return "DuplicateName";
            }
        }

        return "OK";
    }
}

Does anyone notice what the error is?

CodePudding user response:

You are mixing two incompatible frameworks: Spring and Mockito. Chooes either one, but not both. Here's the test with Mockito only:

@ExtendWith(MockitoExtension.class)
public class CategoryServiceTest {

    @Mock
    private CategoryRepository categoryRepository;

    @InjectMocks
    private Cate

Note only one extension and @Mock instead of @MockBean.

  • Related