How to test a Try[T] with ScalaTest correctly?

后端 未结 3 1875
死守一世寂寞
死守一世寂寞 2020-12-20 16:11

I have a method that returns a Try object:

def doSomething(p: SomeParam): Try[Something] = {
  // code
}

I now want to test th

相关标签:
3条回答
  • 2020-12-20 16:17

    Just check to see that it is the success type with your return value:

    maybeRes shouldBe Success("moo")
    
    0 讨论(0)
  • 2020-12-20 16:27

    Another possibility is to do

    import org.scalatest.TryValues._
    maybeRes.success.value.bar shouldBe "moo"
    

    This will give a message indicating the Try was not a success, instead of throwing the exception in maybeRes.get.

    The analog exist for Option, Either and PartialFunction (using the relevant import)

    0 讨论(0)
  • 2020-12-20 16:34

    Alternatively

    import org.scalatest.TryValues._
    
    // ... 
    
    maybeRes.success.value should be "moo"
    
    0 讨论(0)
提交回复
热议问题