Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use mockito to mock webdriver?

I want to be able to do unit test for my Selenium integration tests and to do that I need to be able to mock the driver and the elements needed for the tests, this is a quick example of a function that returns the name of the element.

public class demo {

  private WebDriver mockDriver;
  private WebElement mockElement;

  @Before
  public void setUp(){
    this.mockDriver = mock(WebDriver.class);
    this.mockElement = mock(WebElement.class, withSettings().name("elementName"));
    when(this.mockDriver.findElement(By.id("testmock"))).thenReturn(mockElement);
  }

  public String getName(String id){
    WebElement testElement = mockDriver.findElement(By.id(id));
    return testElement.getAttribute("name");
  }

  @Test
  public void assertElementName() throws InterruptedException {
    Assert.assertTrue(getName("testmock").equals("elementName"));
  }
}

this gives me a java.lang.NullPointerException on the return in getName(). I am obviously using this wrong but I can't figure out how. Anyone with some experience in this that could point me in the right direction?

like image 904
user2968166 Avatar asked Jun 16 '14 11:06

user2968166


People also ask

Can you mock in selenium?

Moreover you get the benefit of being able to fully control API responses, allowing you to easily simulate even the most intricate scenarios. With the help of mock-server running selenium tests, even in CI, becomes almost as easy as running unit tests, as demonstrated in the selenium tests example.

What can be mocked with Mockito?

Mockito mock method We can use Mockito class mock() method to create a mock object of a given class or interface. This is the simplest way to mock an object. We are using JUnit 5 to write test cases in conjunction with Mockito to mock objects.

Is Selenium a Threadsafe?

That is because Selenium WebDriver is not thread-safe by default. In a non-multithreaded environment, we keep our WebDriver reference static to make it thread-safe. But the problem occurs when we try to achieve parallel execution of our tests within the framework.


1 Answers

You are misunderstanding what this piece of code does:

this.mockElement = mock(WebElement.class, withSettings().name("elementName"));

The withSettings() clause gives the mock object a name, meaning that certain error messages produced by Mockito will use this name. You are not setting any properties on the WebElement object.

So... when your code reaches this part:

return testElement.getAttribute("name");

It returns null because there is no attribute with that value. If you wanted to have an attribute, then you'd need to add something like the following:

when(this.mockElement.getAttribute("name")).thenReturn("elementName");
like image 172
Duncan Jones Avatar answered Sep 24 '22 19:09

Duncan Jones