【问题标题】:Expect that all elements in a Seq throws exception in specs2期望 Seq 中的所有元素都会在 specs2 中引发异常
【发布时间】:2015-11-01 09:36:36
【问题描述】:

如果验证失败,我想通过抛出IllegalArgumentException 来对User 类的构造函数的参数进行一些基本验证。在这种情况下,它是我要验证的电子邮件地址。

为了测试验证,我想测试几个有效的电子邮件地址,并期望它们中的没有会导致抛出异常。我还想测试一些无效的电子邮件地址,并期望它们所有都会导致抛出异常。

这是我到目前为止的代码,用于无效的电子邮件地址:

def throwException = throwAn[IllegalArgumentException].like {
  case e => e.getMessage must contain("Invalid email")
}

Seq(
  new User("Valid name", "joe@@multipleAtSigns.com"),
  new User("Valid name", "a?<bunch>[of]special{characters}@validdomain.tld"),
  new User("Valid name", "withoutanyatsign"),
  new User("Valid name", "123@456.789NumbersInTLD"),
  new User("Valid name", "recepientWithoutDomain@"),
  new User("Valid name", "@NoRecepient")
) must contain(throwException).foreach

我将它们放在Seq 中的原因只是方便;我不想每次都写must throwException,像这样:

new User("Valid name", "joe@@multipleAtSigns.com") must throwException
new User("Valid name", "a?<bunch>[of]special{characters}@validdomain.tld") must throwException
new User("Valid name", "withoutanyatsign") must throwException
new User("Valid name", "123@456.789NumbersInTLD") must throwException
new User("Valid name", "recepientWithoutDomain@") must throwException
new User("Valid name", "@NoRecepient") must throwException

我的问题是运行测试时出现错误,这是由抛出的异常引起的:

[error]    java.lang.IllegalArgumentException: Invalid email: joe@@multipleAtSigns.com (User.scala:16)

所以问题是我实际上期望抛出上述异常,我希望我的测试认为抛出的异常成功,但测试错误。

我可以理解为什么会出现测试错误,所以我基本上想知道是否有任何解决方法。或者我可能误解了Traversables 上的匹配器是如何工作的?

【问题讨论】:

    标签: scala specs2


    【解决方案1】:

    可遍历匹配器假定它们正在评估的集合本身不会引发异常。这里就是这种情况,因为一些(或所有)用户输入Seq 会抛出异常。以下将起作用:

    Seq(
      () => new User("Valid name", "joe@@multipleAtSigns.com"),
      () => new User("Valid name", "a?<bunch>[of]special{characters}@validdomain.tld"),
      () => new User("Valid name", "withoutanyatsign"),
      () => new User("Valid name", "123@456.789NumbersInTLD"),
      () => new User("Valid name", "recepientWithoutDomain@"),
      () => new User("Valid name", "@NoRecepient")
    ) must contain((u: (() => User)) => u() must throwException).foreach
    

    不过,我建议将您的验证方法放在 User 类之外,以保持 User 纯类:

    def validate(u: User): Unit = 
      // do the validation 
      ???
    

    我实际上建议完全避免异常并为Users 使用“智能”构造函数

    // you don't even need exceptions :-)
    def user(name: String, email: String): Either[UserCreationError, User] = 
      ???
    

    【讨论】:

      猜你喜欢
      • 2019-04-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2010-12-03
      • 1970-01-01
      • 2011-03-12
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多