1

I have a property in a class

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

And i want test the property fiscal code with two condition. The test is ok if fiscalcode is null or fiscalcode is verified by a method

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

How can i test in a single line with shouldly if one of the two conditions is verified ?

I want use this condition in a test project so the line of code could be

user.FiscalCode.ShouldBeOneOf()

But i can't because null and string are two different types.

Martin Zikmund
  • 38,440
  • 7
  • 70
  • 91
user3401335
  • 2,335
  • 2
  • 19
  • 32

3 Answers3

7

ShouldBeOneOf can not deal an function, so I think the simple way is using ShouldBeTrue

(FiscalCode == null || FiscalClodeIsCorrect(FiscalCode)).ShouldBeTrue();
shingo
  • 18,436
  • 5
  • 23
  • 42
2

I think you can just use basic ||:

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

|| is logical OR operator. This evaluates to true in case at least one of the operands evaluates to true. Also, note that it does short-circuiting which means if the FiscalCode is null it will not call FiscalCodeIsCorrect at all.

Martin Zikmund
  • 38,440
  • 7
  • 70
  • 91
0

what @Martin Zikmund sugessted is right too but in your case both Null and FiscalCodeIsCorrect should be ok. So putting the null validation logic in FiscalCodeIsCorrect should be a better solution, then you wont have to validate if null every time. so here is what i mean

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

now you only have to chack

if (FiscalCodeIsCorrect(FiscalCode) )
{
   //something
}
Alen.Toma
  • 4,684
  • 2
  • 14
  • 31