0

I'm trying write unit tests to code which someone other wrote and I have problem with mocks.

I have something like that:

@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
    }
}

I wrote something like that:

@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());
    }
}

The point of issue is when I run this tests I receive nullPointer on line when(sessionContext.getBusinessObject(A.class).veryfied(anyString()).thenReturn(anyString()); cuz instead of return anyString() it run method veryfied() and from inside this method is throwing nullPointerException.

I don't know what I did wrong.

Erii Asari
  • 165
  • 1
  • 2
  • 8
  • Possible duplicate of [What is a NullPointerException, and how do I fix it?](http://stackoverflow.com/questions/218384/what-is-a-nullpointerexception-and-how-do-i-fix-it) – Nissa Oct 30 '16 at 15:46
  • @SomePerson The point of issue is not that NullPointerException is throwing but why method verified is running, instead of return anyString(). – Erii Asari Oct 30 '16 at 15:54

0 Answers0