WhiteWalker
WhiteWalker

Reputation: 405

Using Mockito but getting null pointer exception when running the test case

I am trying to make test cases junits for the function using selenium webelement as argument.

I am trying to mock the element but this test case is giving error. The method for which I am trying to make test case is this.

 @Override
    public boolean isDownloadStarted(WebDriver driver) {
        boolean isDownloadStarted = false;
        ArrayList<String> tabs = new ArrayList<>(driver.getWindowHandles());
        if (tabs.size() == 1) {
            isDownloadStarted = true;
        }
        return isDownloadStarted;
    }

The test case is which is giving null pointer exception

DownloadStatusListenerImpl status;

@Before
public void before() {
    MockitoAnnotations.initMocks(this);
    status = new DownloadStatusListenerImpl();
}
@Test
    public void testDownloadStatusListenerImpl() {
        Mockito.when(status.isDownloadStarted(Mockito.any(WebDriver.class))).thenReturn(true);
        assertEquals(true, status.isDownloadStarted(Mockito.any(WebDriver.class)));
    }

Upvotes: 1

Views: 261

Answers (1)

Mureinik
Mureinik

Reputation: 312106

You aren't stubbing the status. You could either add a @Spy annotation to it (and stop overwriting it):

@Spy // Annotation added here
DownloadStatusListenerImpl status;

@Before
public void before() {
    MockitoAnnotations.initMocks(this);
    // Stopped overwriting status here
}

Or you could explicitly call Mockito.spy:

@Before
public void before() {
    status = Mockito.spy(new DownloadStatusListenerImpl());
}

EDIT:

Calling when on a method like this will still invoke it, and thus fail. You need to use the doReturn syntax instead:

Mockito.doReturn(true).when(status).isDownloadStarted(Mockito.any(WebDriver.class));

Upvotes: 1

Related Questions