简体   繁体   中英

Nsubstitute return different based on the object properties

I have codes like below. The first call of save(), I want it to throw an exception. And the second call when obj.field="ok", I do not want it to throw exception. How do i achieve this through Nsubstitute?

Try { //Source codes
    workItem.save() //save() has void as return type
} catch (Exception e) {
    if (somecondition){
        workItem.field = "OK";
        workItem.save();
    }
}

// Unit Test
workItem.When(fake => fake.Save()).Do(call => { throw new AggregateException(); });

// How do I make the second call to workItem.save() not throw any exception??

I just found the solution super easy

workItem
          .When(x => x.Save())
          .Do(obj => { if (workItem.Field.Equals("Ok")) throw new AggregateException(new Exception("Assigned")); });

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM