如何模拟 ActionBuilder 的 BodyParser.Default 参数?
Posted
技术标签:
【中文标题】如何模拟 ActionBuilder 的 BodyParser.Default 参数?【英文标题】:How to mock BodyParser.Default parameter of ActionBuilder? 【发布时间】:2019-07-25 08:44:35 【问题描述】:我想为下面的控制器编写测试。
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)))
当我尝试使用 new AuthenticationAction(mockProperties, mock[BodyParsers.Default])
等模拟参数在测试中创建 Action builder(AuthenticationAction) 的实例时,出现此错误:
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])
【问题讨论】:
【参考方案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])
【讨论】:
以上是关于如何模拟 ActionBuilder 的 BodyParser.Default 参数?的主要内容,如果未能解决你的问题,请参考以下文章
在 ActionBuilder 中从 Future 中提取选项