Spring Test Junit抛出空指针异常

时间:2014-02-14 16:34:07

标签: testing junit spring-test

我有这个代码用于测试:

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)

在CVBusinessImpl扩展的CVBusiness包中。

我的问题是为什么CVBusinessImpl中的documentService会抛出Null异常? 谢谢!

2 个答案:

答案 0 :(得分:0)

也许你错过了在测试中使用Spring?如何注入documentService

@RunWith(SpringJUnit4ClassRunner.class)添加到测试类中以在测试中启用Spring。如果你使用autowire应该是全部。您可能还需要对测试@ContextConfiguration注释和/或将@Resource添加到要注入的成员中。

答案 1 :(得分:0)

在您的设置中,您创建了要测试的类:

cvBusinessTest = new CVBusinessImpl();

并且需要其中一项服务:

documentService = mock(DocumentService.class);  

但你从来没有将它们连接在一起。因此,当您的CVBusinessImpl实施调用时:

DocumentSet documentSet = documentService.getDocumentSetById(id)

documentService仍为null

您应该在测试之前连接对象,方法是使用Spring测试运行器或通过设置该字段。您的设置方法中包含以下内容:

cvBusinessTest.setDocumentService(documentService);