Search code examples
azure-functionsnunitmoqazure-ad-graph-apioptional-parameters

how to change the output of a method in a moqed class for a specific test


I have an Azure Function that I want to test, I have several tests working but there is one that doesn't pass. The problem is a call to

await _graphService.GetAllUsersEmailUnverified(authScheme, extensionsAppClientId, tenantDomain, 4);

When Setting up the test, I have this:

[Setup]
public void Setup(){
...
            _graphService = new Mock<IGraphApiService>(MockBehavior.Loose);
...
}

I have tried it with MockBehavior.Strict with no success.

every test that is passing has this line of code:

    _graphService.Setup(o => o.GetAllUsersEmailUnverified(It.IsAny<string>(), It.IsAny<Guid>(), It.IsAny<string>(), It.IsAny<int>(), It.IsAny<UserType>())).Returns(Task.FromResult(userList.AsEnumerable()));

Which is fine. The problem is that in the test that is not passing I have this:

            _graphService
                .Setup(o => o.GetAllUsersEmailUnverified(It.IsAny<string>(), It.IsAny<Guid>(), It.IsAny<string>(), 4, It.IsAny<UserType>()))
.Throws<Exception>();

GetAllUsersEmailUnverified is a method that admits 5 parameters, the last two being optional parameters.

The problem is that when running the mentioned line instead of throwing an exception like I want to, it gives me an error (System.ArgumentNullException : Value cannot be null. (Parameter 'source') and it stops.

I am not keen on changing anywhere out of this particular tests, because it may make the other ones fail.

Things that I have tried:

        .Throws(new Exception());
        .Throws<Exception>();
        .ThrowsAsync(new Exception());

All of them are returning the same error. I suspect that it might have to do with how I set up the Mock, but I am running out of ideas or explanations for this. Any help, please?

Update: This didn't work either: .Callback(() => throw new Exception());


Solution

  • In the end, the test was ok, the problem was that I was rethrowing the exception somewhere else where it wasn't managed. That was what the test was about. Added a few try catch