Test two conditions with shouldly

2k Views Asked by At

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.

3

There are 3 best solutions below

1
shingo On BEST ANSWER

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

(FiscalCode == null || FiscalClodeIsCorrect(FiscalCode)).ShouldBeTrue();
1
Martin Zikmund On

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.

0
Alen.Toma On

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
}