如何在Scala测试中返回值的右值

问题描述 投票:0回答:1

我有一个返回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)
 }

}

现在我为B类和stub方法验证编写测试

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

是否有可能以某种方式将其存在以返回Either函数的右(.....)?

scala scalatest stub either scalamock
1个回答
2
投票

当B取出a的对象时,你可以在BTest类中创建一个A的新对象,并覆盖方法validate,返回右边的任何你想要的东西(a)并覆盖左边的部分返回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"))
} 

或者你可以这样做。正如DarthBinks911所说。

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

这在给定的场景中可以正常工作,但是如果你做了类似mockObject.something的事情,那么它会给你NullPointerException。我建议你覆盖验证方法并返回你想要的东西。

© www.soinside.com 2019 - 2024. All rights reserved.