I'm writing some tests atm for my project. In my test i'm using a service that i inject with dependency injection to the Xunit project.
private readonly Service _service;
public ServicesTests(Service service)
{
_service = service;
}
[Theory]
[ClassData(typeof(PersonData))]
public async void PersonService_ShouldCountPersons(Person person, int expected)
{
//pseudo
// Act.
int actual = await _service.CountPersons(person); //Inside CountPersons is where the method call to the repository takes place.
// Assert.
Assert.Equal(expected, actual);
}
//My Startup
public class Startup
{
public void ConfigureServices(IServiceCollection services)
{
services.AddSingleton<Service>();
}
}
Full exception/error message: Message: System.InvalidOperationException : The ConnectionString property has not been initialized.
Stack Trace:
SqlConnection.PermissionDemand()
SqlConnectionFactory.PermissionDemand(DbConnection outerConnection)
DbConnectionInternal.TryOpenConnectionInternal(DbConnection outerConnection, DbConnectionFactory connectionFactory, TaskCompletionSource1 retry, DbConnectionOptions userOptions) DbConnectionClosed.TryOpenConnection(DbConnection outerConnection, DbConnectionFactory connectionFactory, TaskCompletionSource
1 retry, DbConnectionOptions userOptions)
SqlConnection.TryOpen(TaskCompletionSource`1 retry)
SqlConnection.OpenAsync(CancellationToken cancellationToken)
--- End of stack trace from previous location where exception was thrown ---
SqlMapper.QueryRowAsync[T](IDbConnection cnn, Row row, Type effectiveType, CommandDefinition command) line 473
Repository.GetPersons() line 64
Service.CountPersons(Person person) line 95
Service.CountPersons(Person person) line 130
ServicesTests.PersonService_ShouldCountPersons(Person person, int expected) line 38
This service then call a method in another project, and inside this method i call a repository method that returns some data from the database (using dapper).
When i try to run the test i get the exception "The ConnectionString property has not been initialized." which i understand, my app is not running.. But i'm struggling with how i should set up my database connection for my Xunit test project. Should i add a app.config or appsettings.json or something to get this to work? Or do i need some code to accomplish this?
I hope you understand my question!