BigDataLearner
BigDataLearner

Reputation: 1468

Mocking scala object gives Cannot mock/spy class PQR

I have a scala class where i am accessing a method of an object from third party library.

While unit testing the scala class, I want to mock this third party method call. But I am getting below error

Cannot mock/spy class PQR
Mockito cannot mock/spy because :
 - final class
org.mockito.exceptions.base.MockitoException: 
Cannot mock/spy class PQR
Mockito cannot mock/spy because :
 - final class

My code is as follows

class XYZ {
  def test() : Unit = {
    val ret = PQR.test2("abc") // third party dependency, PQR is object
    ....
  }
}

class XYZSpec extends AnyFlatSpec with Matchers with MockitoSugar {
  it should "create object" in {
    val pqr = mock[PQR.type]
    when(pqr.test2(any[String])) thenReturn "def"
  }
}

How do we fix this?

Upvotes: 0

Views: 345

Answers (0)

Related Questions