Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.1k views
in Technique[技术] by (71.8m points)

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

I have a method that returns a Try object:

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

I now want to test this with ScalaTest. Currently I am doing it like this:

"My try method" should "succeed" in {
  val maybeRes = doSomething(SomeParam("foo"))
  maybeRes.isSuccess shouldBe true
  val res = maybeRes.get
  res.bar shouldBe "moo"
}

However checking for isSuccess to be true looks a bit clumsy because for Options and Sequences there are things like should be(empty) and shouldNot be(empty). I cannot find anything like should be(successful).

Does this exist or is my approach really the way to go?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...