[英]Play Framework & Scala: Mocking a method from with class
I have a method inside my Controller that I want to unit test using Spec2. 我的控制器内部有一个方法,希望使用Spec2进行单元测试。
object MyController extends Controller with MyAuth {
def article(id: String) = {
authenticate {
......
}
}
}
authenticate
is defined in MyAuth
. authenticate
是在MyAuth
定义的。 This function gets the token if available or authenticates and gets the token. 此功能获取令牌(如果可用)或进行身份验证并获取令牌。 I want to mock
authenticate
while unit testing article
. 我想在单元测试
article
模拟authenticate
。 I am not sure how to proceed with this. 我不确定如何进行此操作。 Any pointers will be helpful.
任何指针都会有所帮助。
UPDATE: My approach so far. 更新:到目前为止,我的方法。 I saw this question and overrode authenticate method in MyAuth trait.
我看到了这个问题,并取代了MyAuth特性中的身份验证方法。
trait MyAuthMock {
this: MyAuth =>
override def authenticate ....
}
I also changed MyController
to have class and companion object. 我也将
MyController
更改为具有类和伴侣对象。 Then in my test I used the controller as follows 然后在我的测试中,我按如下方式使用了控制器
new MyController with MyAuthMock
You can refactor your code a little bit to make it easier to test. 您可以对代码进行一些重构,以使其更易于测试。 For example:
例如:
class MyController extends Controller {
def authenticate(...) // abstract method
def article(id: String) = {
authenticate {
......
}
}
}
object MyController extends MyController with RealAuth
In your test class you would do something like: 在测试课程中,您将执行以下操作:
val myTestController = new MyController with FakeAuth
Where FakeAuth is a mock. 其中FakeAuth是模拟的。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.