我试图获得单元测试一个非常简单的ASP.NET MVC测试应用程序,我已经使用最新的EF4 CTP中的代码优先方法构建的句柄。我不是很经验与单元测试/嘲讽等单元测试EF4“代码优先”和存储库
这是我的仓库类:
public class WeightTrackerRepository
{
public WeightTrackerRepository()
{
_context = new WeightTrackerContext();
}
public WeightTrackerRepository(IWeightTrackerContext context)
{
_context = context;
}
IWeightTrackerContext _context;
public List<WeightEntry> GetAllWeightEntries()
{
return _context.WeightEntries.ToList();
}
public WeightEntry AddWeightEntry(WeightEntry entry)
{
_context.WeightEntries.Add(entry);
_context.SaveChanges();
return entry;
}
}
这是IWeightTrackerContext
public interface IWeightTrackerContext
{
DbSet<WeightEntry> WeightEntries { get; set; }
int SaveChanges();
}
...及其实现,WeightTrackerContext
public class WeightTrackerContext : DbContext, IWeightTrackerContext
{
public DbSet<WeightEntry> WeightEntries { get; set; }
}
在我的测试中,我有以下内容:
[TestMethod]
public void Get_All_Weight_Entries_Returns_All_Weight_Entries()
{
// Arrange
WeightTrackerRepository repos = new WeightTrackerRepository(new MockWeightTrackerContext());
// Act
List<WeightEntry> entries = repos.GetAllWeightEntries();
// Assert
Assert.AreEqual(5, entries.Count);
}
而且我MockWeightTrackerContext:当我试图建立一些测试数据,我不能创建一个DbSet<>
,因为它没有构造发生
class MockWeightTrackerContext : IWeightTrackerContext
{
public MockWeightTrackerContext()
{
WeightEntries = new DbSet<WeightEntry>();
WeightEntries.Add(new WeightEntry() { Date = DateTime.Parse("01/06/2010"), Id = 1, WeightInGrams = 11200 });
WeightEntries.Add(new WeightEntry() { Date = DateTime.Parse("08/06/2010"), Id = 2, WeightInGrams = 11150 });
WeightEntries.Add(new WeightEntry() { Date = DateTime.Parse("15/06/2010"), Id = 3, WeightInGrams = 11120 });
WeightEntries.Add(new WeightEntry() { Date = DateTime.Parse("22/06/2010"), Id = 4, WeightInGrams = 11100 });
WeightEntries.Add(new WeightEntry() { Date = DateTime.Parse("29/06/2010"), Id = 5, WeightInGrams = 11080 });
}
public DbSet<WeightEntry> WeightEntries { get;set; }
public int SaveChanges()
{
throw new NotImplementedException();
}
}
我的问题。我用我的整个方法试图嘲弄我的背景,我感到我在吠叫错误的树。任何建议将非常欢迎这个完整的单元测试新手。
感谢您的链接,看起来一个伟大的文章。关于实现一个DbSet的存根,你是说我的MockWeightTrackerContext然后会返回,比如MyDbSetStub而不是DbSet?但是那个类不会实现这个接口。对不起,可能是愚蠢的问题。 ;) – DavidGouge 2010-08-12 09:42:16
非常感谢您花时间解释这一点。这和你提供的链接有很大的帮助。如果我可以再次投票答复,我会。 :D – DavidGouge 2010-08-12 14:16:45
谢谢,MSDN文章实现InMemoryObjectSet正是我需要让我的IContext正常工作。 – kamranicus 2011-02-10 07:07:45