0

I am using scala 2.8 and I am a newbie in scala. I have a challenge testing this endpoint due to injection.

Below is my endpoint

@Singleton
class AuthController @Inject()(
                                cc:ControllerComponents
                                ,authService: IAuthService
                              )
  extends AbstractController(cc){

  def login() = Action.async { implicit request: Request[AnyContent] =>

    val username:String = request.body.asFormUrlEncoded.flatMap(m => m.get("username").flatMap(_.headOption)).getOrElse("")
    val password:String =  request.body.asFormUrlEncoded.flatMap(m => m.get("password").flatMap(_.headOption)).getOrElse("")
    val loginRequest = LoginRequest(username, password)

    authService.validate(loginRequest)
      .flatMap{
        case Some(value) => Future.successful(Ok( value.access_token))
        case None => Future.successful(BadRequest("Something went wrong"))
      }
    }

  def register(): Unit ={
    TODO
  }
}

Below is my Test snippet

class AuthControllerTest  extends PlaySpec   {

  "AuthControllerTest" should {
    "login" in {
       val controller = new AuthController(stubControllerComponents(), null)
      val json = Json.parse("{\"firstName\":\"Foo\", \"lastName\":\"Bar\", \"age\":13}")


      val request = FakeRequest(POST, "/v1/auth/login").withJsonBody(json)
      val home = controller.login().apply(request)

      status(home) mustBe OK
    }

    "register" in {

    }
  }
}
James Z
  • 12,209
  • 10
  • 24
  • 44
Muyinda Rogers
  • 147
  • 3
  • 13

1 Answers1

1

You can consider the following changes in your test-case, those are cosmetics changes

class AuthControllerTest extends PlaySpec with Injecting {
  
  val controller = inject[AuthController]
  
  "AuthControllerTest" should "login" in {
    
      val json = Json.parse(
        """ {
          | "firstName": "Foo",
          | "lastName": "Bar",
          | "age": 13
          |}""".stripMargin)


      val request = FakeRequest(POST, "/v1/auth/login").withJsonBody(json)
      val result = call(controller.login(), request)
      status(result) mustBe OK
    }

    "register" in {

    }
  }
}
Zvi Mints
  • 1,072
  • 1
  • 8
  • 20