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?
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.
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.
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.
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");
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With