8

I have the following class:

class LinkUserService() {

  //** cake pattern **
  oauthProvider: OAuthProvider =>
  //******************

  def isUserLinked(userId: String, service: String) = {
    val cred = oauthProvider.loadCredential(userId)
    cred != null

  }

  def linkUserAccount(userId: String, service: String): (String, Option[String]) = {
    if (isUserLinked(userId, service)) {
      ("SERVICE_LINKED", None)
    } else {
      val authUrl = oauthProvider.newAuthorizationUrl
      ("SERVICE_NOT_LINKED", Some(authUrl))
    }
  }

  def setLinkAuthToken(userId: String, service:String, token:String):String = {
    oauthProvider.createAndStoreCredential(userId, token)
  }

}

Typically I'd use this class in production like so:

val linkService = LinkUserService with GoogleOAuthProvider

When it comes to testing, I want to replace the oauthProvider with a mock such that's been trained by my unit test to respond like so: oauthProvider.loadCredential("nobody") returns null. Is this possible? If so, how would I set up my unit test to do so?

4

2 回答 2

13

你有这个问题是因为你没有完全使用蛋糕图案。如果你写类似

trait LinkUserServiceComponent {
    this: OAuthProviderComponent =>

    val linkUserService = new LinkUserService

    class LinkUserService {
        // use oauthProvider explicitly
        ...
    }
}

trait GoogleOAuthProviderComponent {
    val oauthProvider = new GoogleOAuthProvider

    class GoogleOAuthProvider {
        ...
    }
}

然后你使用这样的模拟:

val combinedComponent = new LinkUserServiceComponent with OAuthProviderComponent {
    override val oauthProvider = mock(...)
}

然后你的问题就消失了。如果您还制作这样的通用接口特征(并使其他组件依赖于接口,而不是实现):

trait OAuthProviderComponent {
    def oauthProvider: OAuthProvider

    trait OAuthProvider {
        // Interface declaration
    }
}

那么你也将拥有通用的可重用和可测试的代码。

这与您的建议非常相似,这确实是蛋糕图案的精髓。

于 2013-09-14T09:03:53.270 回答
0

我能够提出的唯一解决方案是一种委托模拟特征,如下所示:

  trait MockOAuthProvider extends OAuthProvider {
    val mockProvider = mock[OAuthProvider]

    def loadCredential(userId: String) = mockProvider.loadCredential(userId)

    def newAuthorizationUrl() = mockProvider.newAuthorizationUrl

    def createAndStoreCredential(userId: String, authToken: String) = mockProvider.createAndStoreCredential(userId, authToken)

  }

我把它放在我的规范的顶部,然后当我声明我的 LinkUserService 时,我像这样混合这个 Mock 特征:

  val linkUserService = new LinkUserService() with MockOAuthProvider
  val mockOAuth = linkUserService.mockProvider

最后在我的单元测试中,我做了如下的事情:

mockOAuth.loadCredential("nobody") returns null

它有效,但如果我的特征更大,我可以看到成为 PITA

于 2013-09-13T17:02:42.967 回答