1

我想为以下控制器编写测试。

   class DashboardController @Inject()(cc: ControllerComponents,
                                    dashboardDataService: DashboardService,
                                    authenticationAction: AuthenticationAction) 
                                    extends AbstractController(cc) 
                                    {
    def dashboard(): Action[AnyContent] = authenticationAction.async {
        implicit request =>
        Ok(views.html.dashboard(dashboard)))
    }
}

当我尝试使用模拟参数在测试中创建 Action builder(AuthenticationAction) 的实例时new AuthenticationAction(mockProperties, mock[BodyParsers.Default]),我收到了这个错误:

when() requires an argument which has to be 'a method call on a mock'.
[error]    For example:
[error]        when(mock.getArticles()).thenReturn(articles);
[error]
[error]    Also, this error might show up because:
[error]    1. you stub either of: final/private/equals()/hashCode() methods.
[error]       Those methods *cannot* be stubbed/verified.
[error]       Mocking methods declared on non-public parent classes is not supported.
[error]    2. inside when() you don't call method on mock but on some other object.

我试图创建一个实例BodyParsers.Default,而不是模拟它,但它需要一些我无法传递的隐式参数。

如何创建BodyParsers.Default类的实例?

 val mockProperties = mock[ApplicationConfig]
    mockAuthenticationAction returns new AuthenticationAction(mockProperties, mock[BodyParsers.Default])
4

1 回答 1

1

最后,我能够弄清楚。我们必须用一个调用 Action Builder 的方法创建另一个类

class AuthenticationFactory @Inject() (properties: ApplicationConfig, 
parser: BodyParsers.Default) {

   def authenticate = new AuthenticationAction(properties, parser)

}

发布嘲笑工作完美

mockAuthenticationAction.authenticate returns new AuthenticationAction(mockProperties, mock[BodyParsers.Default])

于 2019-07-25T10:35:24.587 回答