【问题标题】:Play Framework & Scala: Mocking a method from with classPlay Framework 和 Scala:使用类模拟方法
【发布时间】:2013-10-25 20:07:18
【问题描述】:

我的控制器中有一个方法,我想使用 Spec2 进行单元测试。

object MyController extends Controller with MyAuth {
  def article(id: String) = {
    authenticate {
      ......
    }
  }
}

authenticateMyAuth 中定义。此函数获取令牌(如果可用)或进行身份验证并获取令牌。我想在单元测试article 时模拟authenticate。我不确定如何进行此操作。任何指针都会有所帮助。

更新:到目前为止我的方法。 我看到了这个 question 并覆盖了 MyAuth 特征中的身份验证方法。

trait MyAuthMock {
  this: MyAuth =>

  override def authenticate ....
}

我还将MyController 更改为具有类和伴随对象。然后在我的测试中我使用控制器如下

new MyController with MyAuthMock

【问题讨论】:

    标签: unit-testing scala playframework mocking


    【解决方案1】:

    您可以稍微重构代码以使其更易于测试。例如:

    class MyController extends Controller {
    
      def authenticate(...) // abstract method
    
      def article(id: String) = {
        authenticate {
            ......
        }
      }    
    }
    
    object MyController extends MyController with RealAuth
    

    在您的测试课中,您会执行以下操作:

    val myTestController = new MyController with FakeAuth
    

    FakeAuth 是模拟的。

    【讨论】:

    • 我用我采用的方法更新了问题。我不确定这里有什么更好的方法,你的还是我的?。
    猜你喜欢
    • 1970-01-01
    • 2016-04-13
    • 1970-01-01
    • 1970-01-01
    • 2016-10-08
    • 2013-05-23
    • 1970-01-01
    • 2016-07-04
    • 1970-01-01
    相关资源
    最近更新 更多