ModelMapper JUnit Mockito выдает исключение NullPointerException - PullRequest
0 голосов
/ 16 октября 2018

Я пытаюсь протестировать метод в классе обслуживания, который использует ModelMapper для преобразования сущности в dto, но в этой строке я получаю исключение NullPointerException mapper.getConfiguration().setMatchingStrategy(MatchingStrategies.STRICT); в классе обслуживания.

Исключение

java.lang.NullPointerException
at pro.budthapa.service.impl.StockCategoryServiceImpl.getStockCategoryByIdAndBusinessGroupId(StockCategoryServiceImpl.java:56)
at pro.budthapa.service.impl.StockCategoryServiceImplTest.WhenCategoryPresent_ShouldReturnCategory(StockCategoryServiceImplTest.java:81)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
at java.lang.reflect.Method.invoke(Unknown Source)
at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:50)
at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:47)
at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:17)
at org.junit.internal.runners.statements.RunBefores.evaluate(RunBefores.java:26)
at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:325)
at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:78)
at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:57)
at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290)
at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71)
at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288)
at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58)
at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268)
at org.junit.runners.ParentRunner.run(ParentRunner.java:363)
at org.mockito.internal.runners.JUnit45AndHigherRunnerImpl.run(JUnit45AndHigherRunnerImpl.java:37)
at org.mockito.runners.MockitoJUnitRunner.run(MockitoJUnitRunner.java:62)
at org.eclipse.jdt.internal.junit4.runner.JUnit4TestReference.run(JUnit4TestReference.java:86)
at org.eclipse.jdt.internal.junit.runner.TestExecution.run(TestExecution.java:38)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:538)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:760)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:460)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:206)

Тестовый класс

@RunWith(MockitoJUnitRunner.class)
public class StockCategoryServiceImplTest {

@Mock
private ModelMapper mapper;

@Mock
private StockCategoryRepository stockCategoryRepository;

@InjectMocks
private StockCategoryServiceImpl stockCategoryService;

@Before
public void setup() {
    mapper = new ModelMapper();
}

@Test
public void WhenCategoryPresent_ShouldReturnCategory() throws Exception {
    int bgId = 10;
    int categoryId = 5;

    StockCategory sc = new StockCategory();
    sc.setCategoryId(categoryId);
    sc.setBusinessGroupId(String.valueOf(bgId));
    sc.setDescription("Test Item");

    Mockito.when(stockCategoryRepository.findByCategoryIdAndBusinessGroupId(categoryId, String.valueOf(bgId))).thenReturn(Optional.of(sc));

    StockCategoryDto result = stockCategoryService.getStockCategoryByIdAndBusinessGroupId(categoryId, bgId);

    assertEquals(5, result.getCategoryId() );
    assertEquals(10, result.getBusinessGroupId());
    assertNotNull(result.getDescription());
    Mockito.verify(stockCategoryRepository, Mockito.times(1)).findByCategoryIdAndBusinessGroupId(categoryId, String.valueOf(bgId));
}

}

Сервисный класс

@Service
public class StockCategoryServiceImpl implements StockCategoryService {

private ModelMapper mapper;
private StockCategoryRepository stockCategoryRepository;

public StockCategoryServiceImpl(ModelMapper mapper, StockCategoryRepository stockCategoryRepository) {
    this.mapper = mapper;
    this.stockCategoryRepository = stockCategoryRepository;
}

@Override
public StockCategoryDto getStockCategoryByIdAndBusinessGroupId(int categoryId, int bgId) {

    Optional<StockCategory> cat = stockCategoryRepository.findByCategoryIdAndBusinessGroupId(categoryId, String.valueOf(bgId));
    if(cat.isPresent()) {

        //getting NullPointerException at this line        
    mapper.getConfiguration().setMatchingStrategy(MatchingStrategies.STRICT);

        return mapper.map(cat.get(), StockCategoryDto.class);
    }

    StockCategoryDto dto = new StockCategoryDto();
    dto.setMessage("Category not found for given id: "+categoryId);
    return dto;
}

} * * тысяча двадцать-один

1 Ответ

0 голосов
/ 16 октября 2018

Вы не должны переназначать свой смоделированный ModelMapper в setup метод.Удалите этот метод

И я не могу найти в вашем коде определения макета для mapper.getConfiguration()

when(mapper.getConfiguration()).thenReturn(...)

Вы должны сообщить его mockito.

...