2014-02-14 2 views
-1

У меня есть этот код для тестирования:Spring Test Junit бросает исключение нулевой указатель

private static final Integer documentSetId = 1143; 
private static final Integer dsLifeCycleStateId = 1; 
private static final String dsLifecycleState = "CVS_CREATED"; 

CVBusiness cvBusinessTest; 


DocumentService documentService; 

DocumentSetRepository documentSetRepository; 

private DocumentSet documentSet; 

private DSLifeCycleState dsLifeCycleState; 

@Before 
public void setUp(){ 
    cvBusinessTest = new CVBusinessImpl(); 
    documentService = mock(DocumentService.class); 
    documentSetRepository = mock(DocumentSetRepository.class); 

    documentSet = new DocumentSet(); 
    dsLifeCycleState = new DSLifeCycleState(); 

    documentSet.setActive(true); 
    documentSet.setDocumentSetId(documentSetId); 
    documentSet.setMarkedForTranslation(false); 

    dsLifeCycleState.setDsLifeCycleStateId(dsLifeCycleStateId); 
    dsLifeCycleState.setLabel(dsLifecycleState); 

    documentSet.setDsLifeCycleState(dsLifeCycleState); 

    when(documentService.getDocumentSetById(documentSetId)).thenReturn(documentSet); 
    when(documentService.updateDocumentSet(documentSet)).thenReturn(documentSet); 
    when(documentSetRepository.findOne(documentSetId)).thenReturn(documentSet); 
} 

@Test 
public void markedForTranslationTest() { 

    boolean retValue = true; 

    DocumentSet docSet = documentService.getDocumentSetById(documentSetId); 
    dsLifeCycleState = docSet.getDsLifeCycleState(); 

    if (dsLifeCycleState.getLabel().equals(LifeCycleStateEnum.CVS_CREATED.message()) && docSet.isActive() && !docSet.isMarkedForTranslation() && ((docSet.getfDR() == null) || docSet.getfDR().equals(""))){ 
     documentSet.setMarkedForTranslation(true); 
     retValue = documentService.updateDocumentSet(documentSet) != null; 
    } 

    // retValue = cvBusinessTest.markedForTranslation(documentSetId); 

    assertTrue(retValue); 

} 

и когда я бегу JUnit, он закончил с ошибками: java.lang Исключение нулевого указателя.

Какие ошибки указывает метод сильфона

DocumentSet documentSet = documentService.getDocumentSetById (ID)

, который находится в пакете CVBusiness продлен CVBusinessImpl.

Мой вопрос, почему documentService в CVBusinessImpl выбрасывает исключение Null? Спасибо!

+1

Можете ли вы разместить исключение? – Augusto

+0

Где происходит исключение, какая строка? –

+0

Исключение происходит, когда я раскомментирую эту строку: retValue = cvBusinessTest.markedForTranslation (documentSetId); и ссылается на строку CVBusiness.java 100, которая содержит этот метод. У меня есть сообщение выше (DocumentSet documentSet = documentService.getDocumentSetById (id)) – wolver

ответ

0

Возможно, вы пропустили использовать Spring в своем тесте? Как вводится documentService?

Добавить @RunWith(SpringJUnit4ClassRunner.class) в тестовый класс, чтобы включить весну в тесте. Если вы используете autwire, это должно быть все. Вам также может понадобиться аннотация для @ContextConfiguration для вашего теста и/или добавить @Resource членам, которые будут введены.

+0

Да, у меня есть @RunWith (SpringJUnit4ClassRunner.class), но я думаю, что проблема заключается в инъекции documentService , Я не включаю контекстную конфигурацию xml. Должен ли я создать mock-экземпляр documentService в контексте conf xml? Потому что я думал, что уже сделал это в своем коде, так как он выше – wolver

+0

Как ваша инъекция происходит в производстве? Autowired, набор средств? XML или аннотация? Используйте аналогичную настройку в своем тесте (небольшой XML-файл, некоторые аннотации @Resource в вашем тесте, ...) –

0

В вашей установки, вы создаете класс для теста:

cvBusinessTest = new CVBusinessImpl(); 

и одна из услуг, которые она требует:

documentService = mock(DocumentService.class); 

, но вы никогда не соединять их вместе. Поэтому, когда ваш CVBusinessImpl реализация вызовов:

DocumentSet documentSet = documentService.getDocumentSetById(id) 

documentService еще null.

Перед тестированием необходимо провести проводку своих объектов либо с помощью тестового бегуна Spring, либо путем установки этого поля. Что-то в вашем методе настройки:

cvBusinessTest.setDocumentService(documentService); 
Смежные вопросы