1

I'm new to unit testing and the language c sharp and I'm trying to unit test by mocking ISessionStorageService to test the HasGlobaladminaccess function but my setup does not seem to work as expected.

public class Context
{
    public asyncTask<bool>HasGlobalAdminAccessAsync(Blazored.SessionStorage.ISessionStorageService sessionStorage)
    {
        return await HasAccessAsync(sessionStorage, Config.Constants.HAS_GLOBALE_ADMIN_ACCESS);
    }

    private async Task<bool> HasAccessAsync(Blazored.SessionStorage.ISessionStorageService sessionStorage, string sessionStorageKey)
    {
        ILogger _logger = Log.ForContext<ContextHelpers>();

        try
        {
            _logger.Debug("HasAccessAsync({sessionStorageKey})", sessionStorageKey);
            var access = await sessionStorage.GetItemAsync<bool>(sessionStorageKey);
            _logger.Debug("HasAccessAsync({sessionStorageKey})::access={access}", sessionStorageKey, access);
            return access;
        }
        catch (Exception ex)
        {
            _logger.Debug("HasAccessAsync({sessionStorageKey})::exception={ex}", sessionStorageKey, ex.Message);
            return false;
        }
    }
}

My test method

private readonly Mock<ISessionStorageService> MockStorage = new Mock<ISessionStorageService>();

[Fact()]
public async Task HasGlobalAdminAccessAsyncTest()
{
    string guid = System.Guid.NewGuid().ToString();
    Context context = new Context();
    MockStorage.Setup(foo => foo.GetItemAsync<bool>(guid)).ReturnsAsync(true);
    var person = await context.HasGlobalAdminAccessAsync(MockStorage.Object);
    Assert.True(person , guid);
}
1
  • What do you want to test with this line: Assert.True(person, guid) ? Commented Aug 13, 2021 at 7:24

1 Answer 1

1

Either use the same value as what's in Config.Constants.HAS_GLOBALE_ADMIN_ACCESS for the GUID value in your test

Or use

foo => foo.GetItemAsync<bool>(It.IsAny<Guid>())

In your Setup call.

As it's written, you have your test set to only accept the exact GUID that is returned from Guid.NewGuid() in your test, so it's not going to work in general.

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.