如何检查Failure [T]中包含哪个异常?

时间:2016-10-15 11:12:04

标签: scala scalatest

我想知道使用ScalaTest检查失败的describe('Service: MyService', function() { beforeEach(module('CustomMatchers')); describe('service: MyService', function() { beforeEach(inject(function(_MyService_, _AnotherService_) { MyService = _MyService_; AnotherService = _AnotherService_; spyOn(AnotherService, 'mySpy'); jasmine.addMatchers({ toContain: function() { return { compare: function(actual, expected){ var result = { pass: actual.includes(expected) }; if(result.pass) { result.message = "Success: Expected first arguments '" + actual + "' to contain '"+ expected +"'."; } else { result.message = "Failour: Expected first arguments '" + actual + "' to contain '"+ expected +"'."; } return result; } } } }); })); it('expect AnotherService.mySpy toHaveBeenCalled', function() { MyService.myFunction('fooBar', 'barBaz'); //This should pass expect(AnotherService.mySpy.calls.argsFor(0)[0]).toContain('foo'); //This should fail expect(AnotherService.mySpy.calls.argsFor(0)[0]).toContain('helloWorld'); }); }); }); 内容的最佳方法。我现在正在做的事情是这样的:

Try

正如您所看到的,我只是解开异常并手动抛出它。是否有更惯用的方式来实现同样的目标?

2 个答案:

答案 0 :(得分:4)

我会选择不会真正抛出异常的东西,因为Failure结果只是另一个可以匹配的结果:

"Subject" should "throw proper exceptions.." in {
  val tryValue = // some method call...
  tryValue shouldBe a[Failure[_]]
  tryValue.failed.get shouldBe an[IllegalArgumentException]
}

以上将断言分开:对于没有发生故障的情况以及发生错误故障的情况,您会看到不同的测试失败。

答案 1 :(得分:1)

希望这是有帮助的

   Try(1 / 0) match {
          case Success(success) =>
          case Failure(error)   => println(error.getClass.getName)

        }

结果: java.lang.ArithmeticException