简体   繁体   English

如何使用Mockito模拟WebDriver?

[英]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. 我希望能够对Selenium集成测试进行单元测试,并且做到这一点,我需要能够模拟驱动程序和测试所需的元素,这是一个返回元素名称的函数的快速示例。 。

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() . 这给了我getName()返回的java.lang.NullPointerException 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? 任何在这方面有经验的人都可以为我指明正确的方向?

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. withSettings()子句为模拟对象命名,这意味着Mockito生成的某些错误消息将使用该名称。 You are not setting any properties on the WebElement object. 没有WebElement对象上设置任何属性。

So... when your code reaches this part: 所以...当您的代码到达这一部分时:

return testElement.getAttribute("name");

It returns null because there is no attribute with that value. 它返回null,因为没有具有该值的属性。 If you wanted to have an attribute, then you'd need to add something like the following: 如果要具有属性,则需要添加如下内容:

when(this.mockElement.getAttribute("name")).thenReturn("elementName");

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM