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?
Add a comment
|
2 Answers
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]