这是隐式参数 - 找不到参数的隐式值

this as implicit parameter - could not find implicit value for parameter

我一直在尝试将 WebBrowser 作为 Selenium ScalaTest 规范中的隐式参数传递,但它失败了。我有一个用于所有测试的基础 superclass:

abstract class BaseSpec extends FunSpec with WebBrowser with ShouldMatchers {
  implicit val webDriver: WebDriver = new FirefoxDriver
}

然后我有一个页面对象,它有一个带有隐式 WebBrowser 参数的方法:

object LoginPage extends Page {
  def login(username: String, password: String) (implicit browser : WebBrowser ) = {      
    //...
  }

然后我想从实际规范中调用 login 方法。由于规范 class 通过其 BaseSpec superclass 实现了 WebBrowser 特性,我希望调用该方法的规范实例被解析为隐式 WebBrowser:

class LoginSpec extends BaseSpec {

  it("Should fail on invalid password") {
    LoginPage login("wrong username", "wrong password")
    assertIsOnLoginPage()
  }
}

但是由于编译错误而失败:

could not find implicit value for parameter browser: org.scalatest.selenium.WebBrowser

在线LoginPage login("wrong username", "wrong password")

我是否总是需要明确提供 this 作为 WebBrowser 参数值,还是有更好的方法?

class LoginSpec 中创建一个隐式 val,如下代码所示:

trait WebBrowser
class WebDriver
class FunSpec
trait ShouldMatchers
class FirefoxDriver extends WebDriver

abstract class BaseSpec extends FunSpec with WebBrowser with ShouldMatchers {
  implicit val webDriver: WebDriver = new FirefoxDriver
}

trait Page

object LoginPage extends Page {
  def login(username: String, password: String)(implicit browser: WebBrowser) = {
    println(username, password)
  }
}

class LoginSpec extends BaseSpec {
  implicit val browser: WebBrowser = this
  def fun = {
    LoginPage login("wrong username", "wrong password")
  }
}

object ImplicitThis {
  def main(args: Array[String]) {
    new LoginSpec().fun
  }
}

这可以编译,并且工作正常。

As the spec class implements the WebBrowser trait via its BaseSpec superclass I expect the spec instance calling the method to be resolved as the implicit WebBrowser

this 不能作为隐式自动使用,但您可以轻松添加它:

abstract class BaseSpec extends FunSpec with WebBrowser with ShouldMatchers {
  implicit def webBrowser: WebBrowser = this
  implicit val webDriver: WebDriver = new FirefoxDriver
}