Shivam Sahil
Shivam Sahil

Reputation: 4921

Mocking HTTP request (POST request) in Scala (using requests-scala)

I am using requests-scala module to make HTTP requests as shown below:

object AEMUtility {
    ....
    def getJWTToken() {
    ....
    val response = requests.post(
      s"$imsExp/ims/exchange/jwt/",
      headers = Map(
        "Content-Type" -> "application/x-www-form-urlencoded"
      ),
      params = Map(
        "client_id" -> clientId,
        "client_secret" -> clientSecret,
        "jwt_token" -> token
      )
    )
    }
}

I want to mock the post request function for writing a Unit test by: checking the arguments passed in the Mock function and returning a dummy response.

Is there a way to mock installed dependency in scala?

I tried :

"authorize" should "return JWT token if request is valid" in {
    val postMock = mock[requests.post]

  }

but this gives me error: Cannot resolve symbol post

Upvotes: 0

Views: 459

Answers (1)

AminMal
AminMal

Reputation: 3173

The error you got is because requests.post is an instance of Requester (see in source code), mock expects a type parameter. You can't pass an object to it, you can mock its classes, traits, etc. So what you should probably do is trying to mock the case class:

val requester = mock[requests.Requester]

Or the BaseSession trait, which contains the post, get and other methods.

val session = mock[requests.BaseSession]

Or the Session case class, which is the implementation of the BaseSession trait.

val session = mock[requests.Session]

I'm not sure anyways, the library doesn't look test-friendly to me.

Upvotes: 1

Related Questions