Reputation: 113
I have a problem with unit testing data access layer. I query the database via stored procedures, so now I can't use Entity Framework in-memory database because in-memory database is not a relational database. Also, I read that I have to use integration tests but I can't find any example with testing using stored procedure.
So my question is how to test data access layer, do I need to create a test database that is same as my real database?
This is my code for data access layer:
public class Repository<TEntity> : IRepository<TEntity> where TEntity : Domains.Users
{
private DbSet<TEntity> dbSet;
private readonly DbContext context;
public Repository(DbContext context)
{
this.context = context;
dbSet = context.Set<TEntity>();
}
public void Add(TEntity entity)
{
if (entity is Domains.Users)
{
SqlParameter param1 = new SqlParameter();
param1.ParameterName = "@Adress";
param1.DbType = System.Data.DbType.String;
param1.Value = (entity as Domains.Users).Adress;
SqlParameter param2 = new SqlParameter();
param2.ParameterName = "@Email";
param2.DbType = System.Data.DbType.String;
param2.Value = (entity as Domains.Users).Email;
SqlParameter param3 = new SqlParameter();
param3.ParameterName = "@Name";
param3.DbType = System.Data.DbType.String;
param3.Value = (entity as Domains.Users).Name;
SqlParameter param4 = new SqlParameter();
param4.ParameterName = "@Lastname";
param4.DbType = System.Data.DbType.String;
param4.Value = (entity as Domains.Users).Lastname;
context.Database.ExecuteSqlCommand("sp_AddUser @Adress, @Email, @Name, @Surname", param1, param2, param3, param4);
}
}
}
Upvotes: 4
Views: 1564
Reputation: 2836
My advice is to use test (real) database (depending on the policies in your firm it can be database on a test server or you can use local instance of the database provider on your dev machine .. etc).
The point of the integration tests are to verify that your application is working stable as single unit. The test env. must be as close as possible to the production evn. which means a real database. EF in memory database representation is no good for that.
You can check also component tests. They are like the integration tests, but with them you don't test the application as a unit, but the major components of the application like repositories, services .. etc, on the other side with integration test you will most like test the REST api endpoints(in the context of REST application).
Some notes on integration/component tests
Examples for integration tests
If you are developing REST api (just example). This are very basic test case examples which are not to be taken as 100% best practices. Just to have a glance of what they could be.
NOTE: In some cases we use the in memory representation only in the begging of the application for some prototyping before we start to develop the actual database.
Upvotes: 3