Here is my class:
public class AuditInfo
{
public String ActionDescription { get; set; }
public String ActionWho { get; set; }
public BasicProjectProfile Project { get; set; }
public AuditInfo ()
{ }
public void SaveInfo ()
{
using (CIHEntities _dbContext = new CIHEntities())
{
AuditInfoEntity aie = new AuditInfoEntity();
aie.ActionDescription = this.ActionDescription;
aie.ActionWhen = DateTime.Now;
if (this.ActionWho != null)
{
aie.ActionWho = this.ActionWho;
}
else
{
aie.ActionWho = "Not Specified";
}
aie.ProjectAssoc = _dbContext.ProjectEntity
.Where(r => r.Id == this.Project.Id)
.First();
_dbContext.SaveChanges();
}
}
}
CIHEntities is a Entity Framework Database.
I would like to unit test the SaveInfo method but it shouldn’t actually save to the Database. How Can this be done?
Thanks
Eric
use the Repository pattern and move the responsibility for saving the enity to the Repository:
write an interface for your repository:
then your implemention:
then make your client code that takes a repository as a parameter will be something like this
Your real application can use the default constructor which will use the RealRepository while you unit tests can can pass a Fake Repository implementation that doesn’t talk to the database (or even better use a Mocking framework like Moq).
This is the basic concept, you can improve it to have a Generic Repository, use UoW pattern … You can read more about it in this msdn article: Testability and EF