0

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?

BigDataLearner
  • 1,388
  • 4
  • 19
  • 40
  • 1
    Does this answer your question? [Mocking scala object](https://stackoverflow.com/questions/3576272/mocking-scala-object) – Gaël J Mar 29 '23 at 19:58
  • 1
    PQR is an object, so you can't mock it's behaviour because it's a singleton class. You might want to wrap it with a class and then mock the class that wraps your object – mbehram Mar 29 '23 at 23:12

0 Answers0