1

I want to write the test for the following controller.

   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)))
    }
}

When I tried to create an instance of Action builder(AuthenticationAction) inside the test with mock parameters like new AuthenticationAction(mockProperties, mock[BodyParsers.Default]), I got this error:

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.

I tried to create an instance of BodyParsers.Default, instead of mocking it, but it needs some implicit parameter which I am not able to pass it.

How to create an instance of BodyParsers.Default class?

 val mockProperties = mock[ApplicationConfig]
    mockAuthenticationAction returns new AuthenticationAction(mockProperties, mock[BodyParsers.Default])
Mario Galic
  • 47,285
  • 6
  • 56
  • 98
Tausif Sayyad
  • 248
  • 1
  • 9

1 Answers1

1

Finally, I am able to figure it out. we have to create another class with a method which will call Action Builder

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

   def authenticate = new AuthenticationAction(properties, parser)

}

Post that mocking workes perfectly

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

Tausif Sayyad
  • 248
  • 1
  • 9