java 使用Mockito运行服务测试时出现NullPointerException

tzcvj98z  于 2022-12-28  发布在  Java
关注(0)|答案(1)|浏览(218)

这是我的测试类,我在其中创建了MockBean并将其注入到服务对象中:

@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");
    }
}

当我尝试运行这个测试时,发生了NullPointerException:

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)

这是我的服务类,方法为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";
    }
}

有人注意到错误是什么吗?

9gm1akwq

9gm1akwq1#

您混合了两个不兼容的框架:Spring和Mockito。选择其中一个,但不能同时选择两个。下面是仅使用Mockito的测试:

@ExtendWith(MockitoExtension.class)
public class CategoryServiceTest {

    @Mock
    private CategoryRepository categoryRepository;

    @InjectMocks
    private Cate

请注意,只有一个扩展名和@Mock,而不是@MockBean

相关问题