单元测试和存根使用sessionContext.getBusinessObject调用内部方法

时间:2016-10-30 08:54:14

标签: java unit-testing

我正在尝试将单元测试写入其他人编写的代码中,并且我对模拟有问题。

我有类似的东西:

@Stateless
public class ABean implements A {


    @Resource
    private SessionContext context;


    // UPLOAD FILE AND PARSING

    @Override
    public Long methodX(final String name) {

        //do Something

        final String status = context.getBusinessObject(A.class).veryfied(name);

        //do Something
        final int id = context.getBusinessObject(A.class).initiate(name);
        final String result = context.getBusinessObject(A.class).doIt(id);
        //doSomething
        context.getBusinessObject(A.class).clean(id);

        return result;
    }


    @Override
    public String veryfied(final String name){
    //do Something
    }

    @Override
    public int initiate(final String name){
        //do Something
    }

    @Override
    public String doIt(final int id){
        //do Something
    }

    @Override
    public void clean(final String name){
        //do Something
    }
}
我写了类似的东西:

@RunWith(PowerMockRunner.class)
public class ABeanTest {

    @Mock
    private SessionContext sessionContext;

    @InjectMocks
    private ABean aBean = new aBean();

    @Test
    public void uploadFile() throws Exception {

        when(sessionContext.getBusinessObject(A.class)).thenReturn(new ABean());

        when(sessionContext.getBusinessObject(A.class).veryfied(anyString()).thenReturn(anyString());
        when(sessionContext.getBusinessObject(A.class).initiate(anyString())).thenReturn(anyInt()));
        when(sessionContext.getBusinessObject(A.class).doIt(anyInt()).thenReturn(anyString());
        doNothing().when(sessionContext.getBusinessObject(A.class)).clean(anyInt());


        aBean.methodX(testName);

        verify(sessionContext.getBusinessObject(A.class), atLeastOnce()).initiateParsing(anyString());
    }
}

问题在于,当我运行此测试时,我在行when(sessionContext.getBusinessObject(A.class).veryfied(anyString()).thenReturn(anyString());上收到nullPointer而不是返回anyString()它运行方法veryfied(),并且从此方法内部抛出nullPointerException。

我不知道我做错了什么。

0 个答案:

没有答案