0

I'm querying a third-party SDK with a fully async-await method and SDK returns an AggregateException in a normal scenario. In AggregateException inner exception will be a type of ABCException.

But while mocking the same code in unit test cases with Moq and XUnit it will return ABCException directly.

This is the code part for the catch block:

public async Task<Response> ExecuteAsync(IFunction function)
{
    try
    {
        return await InvockAsync(function, location);
    }
    catch (AggregateException ex)
    {
        ex.Handle(e =>
        {
            if (e is ABCException)
            {
                DoSomething();
            }
        }
    }
    catch (ABCException ex)
    {
        DoSomething();
    }
}

This is the code block for the unit test case:

public async Task UnitTest()
{
    // Arrange
    var mockService = new Mock<IService>();
    mockService.Setup(x => x.InvockAsync(It.IsAny<IFunction>())).ReturnsAsync(new Response());

    var instance = new OtherService(mockService.Object);

    Func<Task> func = async () => await instance.ExecuteAsync(data);

    //Act
    var data = await Assert.ThrowsAsync<AggregateException>(func);

    //Assert
    Assert.IsType<AggregateException>(data);
}

In the above code, a normal call comes AggregateException and unit test cases call comes into ABCException.

  • According to my understanding you are mocking the `ExecuteAsync` itself not the dependency `InvockAsync`. Is this what you really want? – Peter Csala Feb 08 '21 at 08:06
  • Also `.Result(new Response())` is really weird. Did you mean `.Setup(...).Returns(Task.FromResult(new Response()))` or ``.Setup(...).ReturnsAsync(new Response())``. If I understand your intent correctly then you should call `Throws` or `ThrowsAsync` instead of setting the return object. – Peter Csala Feb 08 '21 at 08:12
  • @PeterCsala Thanks for responding. I have updated the above code. In the above code new Response() is not proper so it throws `AggregateException` but at `var data = await Assert.ThrowsAsync(func);` I will get `ABCException` instead of `AggregateException`. – manish bhalodiya Feb 08 '21 at 09:18
  • Sorry, but I don't get it. If you have set up your `InvockAsync` to return a concrete value then why do expect any exception? – Peter Csala Feb 08 '21 at 10:15
  • @manishbhalodiya It appears your code example needs update to present the exact problem. The mock setup is not configured to throw exception, perhaps you missed something while simplifying the problem scenario. – tyrion Feb 08 '21 at 18:46

0 Answers0