1

a have this code:

var response = await await _service.GetProfile(code) .ContinueWith(async task =>{ if(task.IsFaulted) { ///... anyway return object; } }); 

I can't get to IsFault in my unit test. Can you help me build this unit test? I'm using Xunit and NSubstitute

3
  • 2
    Don't use ContinueWith at all; use await instead. Commented Nov 17, 2022 at 21:08
  • Use await _service.GetProfile(code) for unit testing Commented Nov 18, 2022 at 6:51
  • It's not clear from the question whether the code you show is the test or the code you want to write a test for. Commented Nov 18, 2022 at 20:34

1 Answer 1

1

Don't use ContinueWith. Just use await. A faulted Task will throw an exception on await that you can catch and handle.

try { var response = await _service.GetProfile(code); // Here Task is complete without an exception } catch(Exception ex) { // Task has faulted return object; } 

Note that your test method has to be marked async.


In order to write unit tests for asynchronous code without using await, use synchronization objects like a ManualResetEvent.

See my answer here: "Thread was being aborted." in test that tests code that fires a delegate on a background thread

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.