How to initialize variable for FindBy annotation in Selenium with Kotlin?

318 Views Asked by At

What is the best way to initialize a variable with the Selenium's FindBy annotation in Kotlin?

Something like

@FindBy(id = "example")
private lateinit var button: WebElement

or

@FindBy(id = "example")
private val button: WebElement? = null

or

@FindBy(id = "example")
private var button: WebElement? = null

or something else?

Note that all the previous methods works perfectly.

2

There are 2 best solutions below

1
Joffrey On

The second option likely will not work, because the val is already initialized to null and cannot be changed.

I believe using the lateinit is the way to go in this case. It's meant for this purpose mainly.

0
cutiko On

You want late init because if the annotation fails to find it you will have a more understandable exception rather than null pointer exception