1

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)));
    }
0

1 Answer 1

1

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));
Sign up to request clarification or add additional context in comments.

3 Comments

using Spy is also giving same error NullPointerException only.
@WhiteWalker Arg, my mockito-fu is out of practice. See my edited answer.
Same result null pointer exception even after using doReturn as you suggested.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.