代码之家  ›  专栏  ›  技术社区  ›  user3401335

用shouldly测试两个条件

  •  1
  • user3401335  · 技术社区  · 7 年前

    public class User {
        public string FiscalCode {get; set;}
    }
    

    我想用两个条件测试属性财政代码。

    public bool FiscalCodeIsCorrect(string fiscalcode) 
    {
        ....
    }
    

    如果两个条件中的一个得到验证,我如何使用shouldly在一条线上进行测试?

    user.FiscalCode.ShouldBeOneOf()
    

    但我不能,因为 null string

    3 回复  |  直到 7 年前
        1
  •  7
  •   shingo    7 年前

    ShouldBeOneOf 不能处理函数,所以我认为简单的方法是使用 ShouldBeTrue

    (FiscalCode == null || FiscalClodeIsCorrect(FiscalCode)).ShouldBeTrue();
    
        2
  •  2
  •   Martin Zikmund    7 年前

    || :

    if ( FiscalCode == null || FiscalCodeIsCorrect(FiscalCode) )
    {
       //something
    }
    

    是逻辑或运算符。这评估为 true 符合事实的 . 另外,请注意,它会短路,这意味着 FiscalCode null FiscalCodeIsCorrect 完全

        3
  •  0
  •   Alen.Toma    7 年前

    Null FiscalCodeIsCorrect 应该没问题。所以把 null 中的验证逻辑 应该是一个更好的解决方案,这样您就不必每次都验证是否为null。

    public bool FiscalCodeIsCorrect(string fiscalcode) 
    {
        if (fiscalcode == null)
           return true;
        //....You code here
    }
    

    现在你只需要查克

    if (FiscalCodeIsCorrect(FiscalCode) )
    {
       //something
    }