Unit testing 游戏框架&;Scala:用类模拟来自的方法
我的控制器中有一个方法,我想使用Spec2进行单元测试Unit testing 游戏框架&;Scala:用类模拟来自的方法,unit-testing,scala,playframework,mocking,Unit Testing,Scala,Playframework,Mocking,我的控制器中有一个方法,我想使用Spec2进行单元测试 object MyController extends Controller with MyAuth { def article(id: String) = { authenticate { ...... } } } MyAuth中定义了authenticate。此函数获取令牌(如果可用),或者验证并获取令牌。我想在单元测试文章时模拟身份验证。我不知道如何进行这项工作。任何提示都会有帮助 更新:我目前的
object MyController extends Controller with MyAuth {
def article(id: String) = {
authenticate {
......
}
}
}
MyAuth
中定义了authenticate
。此函数获取令牌(如果可用),或者验证并获取令牌。我想在单元测试文章
时模拟身份验证
。我不知道如何进行这项工作。任何提示都会有帮助
更新:我目前的方法。
我看到了这一点,并在MyAuth trait中重写了authenticate方法
trait MyAuthMock {
this: MyAuth =>
override def authenticate ....
}
我还将MyController更改为具有类和伴生对象。然后在我的测试中,我使用了如下控制器
new MyController with MyAuthMock
您可以稍微重构代码,使其更易于测试。例如:
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是一个mock。您可以稍微重构代码,使其更易于测试。例如:
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是一个模拟。我用我采用的方法更新了这个问题。我不确定你的方法和我的方法哪个更好。我用我的方法更新了这个问题。我不确定在这里什么是更好的方法,你的还是我的?。