So in my unit tests i need to test queries to a database (no i am not mocking these, as i need to check they get the correct data), normal methods that do not contact a database at all and some methods that i can use a mock to the database.
To cope with the database unit tests, i created a class called DbUnitTest, which each unit test class (for a service) can inherit from if it needs to connect to a database.
This class looks like so
[TestClass]
public abstract class DbUnitTest
{
protected IDataContext _context;
[TestInitialize]
public void TestInit()
{
_context = new DataContext();
// drop if exists
if (_context.Database.Exists())
_context.Database.Delete();
// initialize
System.Data.Entity.Database.SetInitializer(new ForceDeleteInitializer(new DbUnitTestInitializer()));
_context.Database.Initialize(true);
}
}
This works, and for each test it deletes the database and creates a new one. I can then insert whatever data i want within each unit test and check that the data is correct.
But now some of my service classes that i am unit testing, do not need a real database, so it seems pointless to delete the database, initialize it etc etc as this takes time.
I thought maybe i could create an attribute against each test, like UseDb and UseMock. Then in my base DbUnitTest class, i could change the method to something like this
[TestClass]
public abstract class DbUnitTest
{
protected IDataContext _dbContext;
protected Mock<IDataContext> _mockContext;
[TestInitialize]
public void TestInit()
{
// How do i check for an attribute here??
if (method has UseDb attribute)
{
_dbContext = new DataContext();
// drop if exists
if (_dbContext.Database.Exists())
.Database.Delete();
// initialize
System.Data.Entity.Database.SetInitializer(new ForceDeleteInitializer(new DbUnitTestInitializer()));
_dbContext.Database.Initialize(true);
}
if (UseMock attribute)
{
// mock context
_mockContext = new Mock<IDataContext>();
}
}
}
But i am unsure of how, or if it is possible to determine if the current unit test method that is running contains a particular attribute?
This would then give me the benefit of each test being able to either create a new database or use a mock.
Can anyone help me.
Btw, i know i could really split the Unit Test classes up into 2 files, but thought this would keep all tests for a service in one place and offers flexibility.
Aucun commentaire:
Enregistrer un commentaire