简体   繁体   中英

Unit test should be failing

I'm trying to write a unit test for GenerateTokenAsync()

public async Task<string> GenerateTokenAsync()
{
    Verify.IsNotNullOrWhiteSpace(ClientId, nameof(ClientId));
    Verify.IsNotNullOrWhiteSpace(ClientSecret, nameof(ClientSecret));
    Verify.IsNotNullOrWhiteSpace(TenantId, nameof(TenantId));

    var clientCredential = new ClientCredential(ClientId, ClientSecret);
    var context = new AuthenticationContext(Constants.AuthenticationContextUrl + TenantId);
    var authResult = await context.AcquireTokenAsync(Constants.AuthResultUrl, clientCredential);

    return authResult?.AccessToken;
}

and there are 3 properties that must have values.

I'm expecting Verify.IsNotNullOrWhiteSpace() to throw an exception but it is not.

This is a static helper class that throws an ArgumentException() .

The test should be failing since no values have been provided for all 3 properties.

I have tried to change the unit test, but not working.

[TestMethod]
public async Task GenerateTokenAsync_WhenExecuted_GeneratesToken()
{
    // Arrange
    var mockAzureClient = new Mock<IAzureClient>();
    mockAzureClient.Setup(m => m.GenerateTokenAsync()).ReturnsAsync(Guid.NewGuid().ToString("N"));

    // Act
    var token = await mockAzureClient.Object.GenerateTokenAsync();

    // Assert
    token.Should().NotBeNullOrWhiteSpace();
}

This might be an XY problem as it looks like you are mocking the subject under test.

In this case I see no need for using Mock to Test the above function. Create an instance and invoke the member under test

[TestMethod]
public async Task GenerateTokenAsync_WhenExecuted_WithoutProperties_ShouldFail() {
    // Arrange
    IAzureClient azureClient = new AzureClient(); //Assuming name here
    ArgumentException actual = null;

    // Act
    try {
        var token = await azureClient.GenerateTokenAsync();
    } catch(ArgumentException ex) {
        actual = ex;
    }

    // Assert
    actual.Should().NotBeNull();
}

You are basically testing an external SDK which is not something you should concern yourself with.

An SDK can easily change, methods and ways of doing things can change as well and you have no control over that. Chances are this code won't work as soon as anything changes.

That code is more than likely covered by tests provided by the SDK authors, in which case what exactly are you achieving with this thing? I can't call it a unit test because it isn't one. It's an integration test and not a very useful one either.

I would suggest you focus on testing the code which calls into the SDK. Make sure you do not call the SDK with empty parameters, that code is yours and you can control it. Test that and leave the SDK testing to its own authors.

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