【问题标题】:How to test a Try[T] in ScalaTest correctly?如何正确测试 ScalaTest 中的 Try[T]?
【发布时间】:2020-06-04 10:39:35
【问题描述】:

我已经检查了帖子中指定的答案 How to test a Try[T] with ScalaTest correctly?

但是,如果我必须在函数调用之后进行任何断言,或者如果我必须检查 for { } yield { } 块中的断言,那么我将遵循以下给定的方法:

  def test(a: Int, b: Int): Try[Int] = Try {
    a / b
  }

  it.should("succeed").in {
    (for {
      res <- test(0, 1)
    } yield {
      assert(res === 0)
      // assume more assertions are to be made
    }) match {
      case Success(value)     => value
      case Failure(exception) => fail(exception)
    }
  }

  it.should("fail").in {
    test(1, 0).failure.exception.getClass.mustBe(classOf[java.lang.ArithmeticException])
  }

上述方法的问题在于,对于成功案例,如果单元测试逻辑中发生任何问题,那么它将显示指向case Failure(exception) =&gt; fail(exception) 行的错误,而不是实际发生错误的行。如果测试用例很大,那么用户将很难找到错误发生的确切位置。

那么有没有更好的方法来对返回Try[T] 的函数进行单元测试而不将断言移到for { } yield { } 块之外?

【问题讨论】:

    标签: scala unit-testing scalatest


    【解决方案1】:

    TryValues 特征(记录在 here)旨在帮助解决此问题:

    class MyTestSpec extends FlatSpec with Matchers with TryValues {
      "tryTest" should "succeed" in {
        // Normal tests
        test(0, 1).isSuccess shouldBe true
        test(1, 1).isFailure shouldBe true
    
        // Use TryValues conversions
        test(0, 1).success.value shouldBe 0
        test(1, 1).failure.exception should have message "should be zero"
      }
    }
    

    【讨论】:

      猜你喜欢
      • 2017-10-22
      • 1970-01-01
      • 1970-01-01
      • 2011-11-05
      • 1970-01-01
      • 2023-03-21
      • 1970-01-01
      • 2015-06-26
      • 2018-08-10
      相关资源
      最近更新 更多