我对Mockito和使用@Spy注释的字段有点混乱。
我想测试这个课程:
@Service
public class CategoryServiceImpl implements CategoryService {
@Autowire
private CategoryRepository categoryRepository;
private BoundMapperFacade<CategoryDTO, Category> boundMapper;
@Autowired
public void createMapper(final Mapper mapper) {
boundMapper = mapper.getMapperFactory().getMapperFacade(
CategoryDTO.class, Category.class);
}
// Rest of methods...
}
所以,我创建了一个测试类,如下所示:
@RunWith(MockitoJUnitRunner.class)
public class CategoryServiceImplTest {
@Mock
private CategoryRepository categoryRepository;
@Spy
private Mapper mapper;
@Spy
private BoundMapperFacade<CategoryDTO, Category> boundMapper;
@InjectMocks
private CategoryServiceImpl categoryServiceImpl;
// Rest of methods...
}
当Mockito实例categoryServiceImpl将categoryRepository注入模拟类但它不知道如何创建boundMapper。这个类依赖于mapper,所以我重写了我的代码:
@RunWith(MockitoJUnitRunner.class)
public class CategoryServiceImplTest {
@Mock
private CategoryRepository categoryRepository;
@Spy
private Mapper mapper;
private BoundMapperFacade<CategoryDTO, Category> boundMapper = spy(mapper.getMapperFactory().getMapperFacade(
CategoryDTO.class, Category.class));
@InjectMocks
private CategoryServiceImpl categoryServiceImpl;
// Rest of methods...
}
但现在问题是在Mockito注入mapper之前执行了boundMapper的创建,所以我得到了一个NullPointerException。
那么,有没有办法创建一个依赖于另一个的间谍类,最后在标记为@InjectMocks的字段中注入最后一个?