Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

395
Views
Test a function throwing an Exception in a Task in xunit

I want to test using xunit a function that run a task and throw in a that task For example :

public void doSomething(){
     Task.Run(() =>
            {
                throw new ArgumentNullException();
            });
}

When I want to test this function by doing this :

[Fact]
public void TestIfTheMethodThrow()
{
   Assert.Throws<ArgumentNullException>(() => doSomething()); // should return true but return false                                                                   
}

I want that the Task.Run() finish completely then the assert can be done. anyone have a solution ?

over 4 years ago · Santiago Trujillo
2 answers
Answer question

0

Raising and handling exceptions using TPL (the Tasks library) is slightly different, than the "standard" exception handling. It is meaningful to evaluate only a completed task, so you need to wait for the completion, even if in this case it is an exception.

Have a look at this MSDN article Exception handling (Task Parallel Library).

You have two different options:

  • add .Wait() to the Task.Run(...)`

    Task.Run(() =>
           {
               throw new ArgumentNullException();
           }).Wait();
    
    
    
  • or wait while the task is completed while(!task.IsCompleted) {}

     var task = Task.Run(() =>
            {
                throw new ArgumentNullException();
            });
    while(!task.IsCompleted) {}

The test result should be then as expected - an exception is thrown.

It could be, that before the Wait your test has passed sporadically - don't be irritated - in this case the task execution was faster than the test check - this is a dangerous source of subtle errors.

over 4 years ago · Santiago Trujillo Report

0

You can write your method using async and await

Read this for reference Asynchronous programming with async and await

The new method look like this, and the caller will decide if want wait or not, if you call with await it will wait the task complete, otherwise it will continue without wait the task completion

public async Task DoSomethingAsync()
{
    if (true)
        throw new ArgumentNullException();
    await FooAsync();
}

In the test:

[Fact]
public async Task TestIfTheMethodThrow()
{
   await Assert.ThrowsAsync<ArgumentNullException>(() => DoSomethingAsync());                
}
over 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!