Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.3k views
in Technique[技术] by (71.8m points)

selenium webdriver select element

I have a select control on my site. I am using page objects to interact with the page. If I do (with the first 2 lines under my class and the selectByValue in my method)

@FindBy(id="foo")
private Select foo;

foo.selectByValue("myValue");

It fails with a null pointer. I also tried without the @FindBy.

Now if I do this in my method it all works fine and selects the correct item

Select foo = new Select(sDriver.findElement(By.id("foo")));
foo.selectByValue("myValue");

Here is the actual web snippet for that control (edited to protect the innocent)

<select id="foo" name="service_name">
    <option selected="selected" value="one">one</option>
    <option value="two">two</option>
    <option value="three">three</option>
</select>

Let me say that I have a work around for my issue but I don't get why the "normal" path is not working.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Thats because the Select class has this constructor:

Select(WebElement element)

See the Javadoc

So if you do something like this:

@FindBy(id="foo")
private WebElement wannabeSelect;
Select realSelect = new Select(wannabeSelect);
realSelect.selectByValue("myValue");

It should work.

BTW, I am using the same approach as you in the "workaround" because I dont wanna cast new WebElement object when I need Select object. But anyways, the

sDriver.findElement(By.id("foo"));

returns WebElement, so thats why its working. You can also do this:

 WebElement wannabeSelect = sDriver.findElement(By.id("foo"));
 Select foo = new Select(wannabeSelect);

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

57.0k users

...