I want to write some unit tests for a method. However, the method references my entity framework. Here is a heavily contrived example of the method I want to test:
public int GetNumberWithName(string name, NWRevalDatabaseEntities entities)
{
int number = (from n in entities.TableOfNumbers
where n.Name == name
select n).First();
return number;
}
The question:
Is there a way for me to instantiate a NWRevalDatabaseEntities object in my testing class without giving it a viable database connection, so all the tables are empty, and then just inserting the entities needed for the test, and never persisting them to a database?
The store for NWRevalDatabaseEntities is a SQLite database, and the auto generated constructors available are:
/// <summary>
/// Initializes a new NWRevalDatabaseEntities object using the connection string found in the 'NWRevalDatabaseEntities' section of the application configuration file.
/// </summary>
public NWRevalDatabaseEntities() : base("name=NWRevalDatabaseEntities", "NWRevalDatabaseEntities")
{
this.ContextOptions.LazyLoadingEnabled = true;
OnContextCreated();
}
/// <summary>
/// Initialize a new NWRevalDatabaseEntities object.
/// </summary>
public NWRevalDatabaseEntities(string connectionString) : base(connectionString, "NWRevalDatabaseEntities")
{
this.ContextOptions.LazyLoadingEnabled = true;
OnContextCreated();
}
/// <summary>
/// Initialize a new NWRevalDatabaseEntities object.
/// </summary>
public NWRevalDatabaseEntities(EntityConnection connection) : base(connection, "NWRevalDatabaseEntities")
{
this.ContextOptions.LazyLoadingEnabled = true;
OnContextCreated();
}
All of which require a connection or connection string (or uses the stored connection string).
If this is not possible, I will look into creating an in-memory SQLite database and then feed that connection to the NWRevalDatabaseEntities constructor. However, this seems like it would be much slower (since it hits the database engine) and unit testing should be fast, and also, will require me to get the database definition code into my application, where it was not previously needed.
I know testing anything with entity frameworks usually go to integration testing, not unit testing. However, these tests don't really test integration - the database query is incredibly simplistic and might as well have been against an array - I just want to check that the right selection of query is made by my method.