Search code examples
scalascalateststubeitherscalamock

How to return a value of Right value of Either in Scala test


I have a method which returns Either[Exception, String]

class A {
    def validate(a: Any) = {
        case a: String => Left(...some.. exception)
        case a: Any => Right(a)
   }
 }

class B(a: A) {
    def callValidate(any: Any) = {
      a.validate(any)
 }

}

Now I write tests for class B and I stub method validate

class BTest  {
   val param: Any = "22"
   val a = mock[A]
   (a.validate _).expects(param).returning(....someValue...) // . this value should be Right(....) of either function. 
} 

Is it possible to stub it that way to return Right(.....) of Either function ?


Solution

  • As B is taking the object of a you can make a new object of A in BTest class and override the method validate to return whatever you want once return Right(a) and to cover the Left part return Left(a).

        class BTest  {
           val param: Any = "22"
           val a = new A{
    override def validate(a:Any) = case _ => Right(a)
    }
       (a.validate _).expects(param).returning(Right("22"))
    } 
    

    or you can do like this. As DarthBinks911 suggested.

    (a.validate _).expects(param).returning(Right("a"))
    

    this will work fine in the given scenario but if you do something like mockObject.something then it will give you NullPointerException. I would suggest you to override the validate method and return what ever you want.