简体   繁体   中英

Using dependency injection in a unit test class

I am using xunit to write unit tests for my web api. My web api uses dependency injection to pass along a DbContext and an IConfiguration as parameters using constructor injection. I would like to be able to do this in my unit tests project so that I can easily have access to the DbContext and IConfiguration. I have read about using a fixture to do this but I have not found a good example on how this would be handled. I have seen articles using the TestServer class but my project targets the .NETCoreApp1.1 framework which won't let me use the TestServer class. Any suggestions here?

Are you sure that you need to use those dependencies in your tests? According to unit testing philosophy consider using some mock frameworks to provide dummy instances of your DbContext and IConfiguration with suitable behavior and values. Try to look into NSubstitute or Moq framework.

The easiest way i've found to create a 'fake' configuration to pass into methods requiring an IConfiguration instance is like this:

[TestFixture]
public class TokenServiceTests
{
    private readonly IConfiguration _configuration;

    public TokenServiceTests()
    {
        var settings = new List<KeyValuePair<string, string>>
        {
            new KeyValuePair<string, string>("JWT:Issuer", "TestIssuer"),
            new KeyValuePair<string, string>("JWT:Audience", "TestAudience"),
            new KeyValuePair<string, string>("JWT:SecurityKey", "TestSecurityKey")
        };
        var builder = new ConfigurationBuilder().AddInMemoryCollection(settings);
        this._configuration = builder.Build();
    }

    [Test(Description = "Tests that when [GenerateToken] is called with a null Token Service, an ArgumentNullException is thrown")]
    public void When_GenerateToken_With_Null_TokenService_Should_Throw_ArgumentNullException()
    {
        var service = new TokenService(_configuration);
        Assert.Throws<ArgumentNullException>(() => service.GenerateToken(null, new List<Claim>()));
    }
}

[This obviously using NUnit as the testing framework]

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