Issue
I have a project that uses Spring MVC. I'm trying to write unit tests for the service module, which is in the architecture of the project. All service classes extend from super class named "BaseService". BaseService is like this:
public abstract class BaseService {
private static final Logger logger = LoggerFactory.getLogger(BaseService.class);
@Autowired(required = true)
private HttpServletRequest request;
@Autowired
private ReloadableResourceBundleMessageSource messageSource;
/*
* Injecting Mapper
*/
@Resource
private Mapper mapper;
...
public <T extends BaseBVO, S extends BaseVO> T voToBvo (S vo, Class<? extends BaseBVO> bvoClass) {
if (vo != null)
{
return (T) mapper.map(vo , bvoClass);
}
else
{
return null;
}
}
now I have a method in the service module that use the method:
"voToBvo (S vo, Class<? extends BaseBVO> bvoClass")
like this:
public List<AdcOptionBVO> findOptionByAyantDroitIdAndProduitId (Long idAyantDroit, String idProduit) {
....
list = listVoToBvo(adcList , AdcOptionBVO.class);
logger.info("Returning List of ayrp count= {}" , list.size());
return list;
}
My test is like this:
@RunWith(MockitoJUnitRunner.class)
public class AdcServiceImplTest{
@Mock
private Mapper mapper;
@Test
public void shouldSuccessFindOptionByAyantDroitIdandProduitId() {
//Given
List<AdcVO> adcVOList = new ArrayList<>();
adcVOList.add(new AdcVO());
List<AdcOptionBVO> listAdcOptionBVO = new ArrayList<>();
listAdcOptionBVO.add(new AdcOptionBVO());
List<BaseBVO> baseBVOs = new ArrayList<>();
//When
when(repository
.finAdcByOptionOrderByRUAndPrio(anyLong(), anyString())).thenReturn(adcVOList);
when(baseService.listVoToBvo(adcVOList, AdcOptionBVO.class)).thenReturn(baseBVOs);
//Then
assertEquals(adcService
.findOptionByAyantDroitIdAndProduitId(anyLong(), anyString()).size(), adcVOList.size());
}
}
I get a java.lang.NullPointerException in BaseService.java when calling the mapper.
@Resource
private Mapper mapper;
the mapper is null!
I want to mock the method:
listVoToBvo(adcList , AdcOptionBVO.class);
Please help.
Solution
The solution is to add constructor for the abstarct class with injected parameter, in my case ( mapper) , then in the service call super(mapper);
in the constructor of the service
so in the tests I mock Mapper mapper, then I instanciate my class in @Before
, so the mapper pass to the abstarct class as a Mock and not null.. It works fine for me. I hope its claire
Answered By - ATEF CHAREF
Answer Checked By - Clifford M. (JavaFixing Volunteer)