使用SQL Server CE 4或SQLite与Entity Framework 4 Code First进行集成测试

Bre*_*ogt 6 sql-server sqlite entity-framework sql-server-ce entity-framework-4

我想从集成测试开始.我正在使用ASP.NET MVC 3应用程序.我正在使用Entity Framework 4 Code First CTP5.我对数据库的集成测试是在一个单独的项目中,类似于MyProject.Data.IntegrationTests.

我打算使用SQL Server CE 4或SQLite.有关使用其中任何一项的建议/提示/意见,我想要完成的任务?

有谁知道我能读到的关于我想要完成的任何体面的文章?并且将非常感谢帮助/反馈.

我正在使用SQL Server 2008作为我的数据库.但是在测试我的存储库时,我想针对上面提到的其中一个数据库测试它们,所以我需要指定连接字符串.

UPDATE

我从服务层(从我的控制器调用)工作,然后服务层将调用我的存储库.例如,下面是我如何添加新闻项:

服务类:

public class NewsService : INewsService
{
   private INewsRepository newsRepository;

   public NewsService(INewsRepository newsRepository)
   {
      this.newsRepository = newsRepository;
   }

   public News Insert(News news)
   {
      // Insert news item
      News newNews = newsRepository.Insert(news);

      // Insert audit entry

      // Return the inserted news item's unique identifier
      return newNews;
   }
}
Run Code Online (Sandbox Code Playgroud)

存储库类:

public class NewsRepository : INewsRepository
{
   MyContext context = new MyContext();

   public NewsRepository()
   {
   }

   public News Insert(News news)
   {
      int newsId = context.Database.SqlQuery<int>("News_Insert @Title, @Body, @Active",
         new SqlParameter("Title", news.Title),
         new SqlParameter("Body", news.Body),
         new SqlParameter("Active", news.Active)
      ).FirstOrDefault();

      news.NewsId = newsId;

      // Return the inserted news item
      return news;
   }
}
Run Code Online (Sandbox Code Playgroud)

我正在使用Entity Framework 4 Code First CTP5和NUnit.NUnit是否有类似于XUnit中的回滚?

Pau*_*aul 2

如果您使用像 XUnit ( http://xunit.codeplex.com/ )这样的测试框架,它带有一个名为 [AutoRollback] 的功能,它将回滚测试中运行的事务,因此您的任何数据都不会改变!

至于如何设置测试,我需要更多地了解如何设置数据访问。您使用了存储库模式吗?(实体框架 4 CTP 4 / CTP 5 通用存储库模式和可单元测试)。如果我能看到你的一些代码将会有所帮助。下面是与 XUnit 的集成测试示例:

private readonly IUserRepository _repository;

public UserRepositoryTests()
{
    _repository = new UserRepository(base._databaseFactory);
}
    
[Fact, AutoRollback]
public void Should_be_able_to_add_user()
{
    var user = new User{Name = "MockName"};
    _repository.Add(user);
    base._unitOfWork.Commit();
    
    Assert.True(user.Id > 0);
}
Run Code Online (Sandbox Code Playgroud)

因此,上面的测试将一个用户添加到我的数据库中,然后检查其 Id 属性以检查 SQL Server 是否自动为其生成了 Id。因为该方法用 AutoRollback 属性修饰,所以该方法结束后数据将从我的数据库中删除!