简体   繁体   English

单元测试实体框架存储库

[英]Unit Testing Entity Framework Repository

I am working with TDD and all is going well. 我正在与TDD合作,目前一切顺利。 When I get to my actual Repository though I don't know how to test this. 当我到达实际的存储库时,虽然我不知道如何进行测试。

Consider the code below - this is what I know I want to write but how do I tackle this in a test first way without doing integration testing. 考虑下面的代码-这是我想写的,但是我如何在不进行集成测试的情况下以测试方式首先解决这一问题。

public class UserDb : IUserDb
{
    public void Add(User user)
    {
        using (var context = new EfContext())
        {
            context.Users.Add(user);

            context.SaveChanges();
        }
    }
}

The link below by forsvarir is what I want to put as an answer. 我想把下面的forsvarir链接作为答案。 How I can do that? 我该怎么做?

http://romiller.com/2012/02/14/testing-with-a-fake-dbcontext/ http://romiller.com/2012/02/14/testing-with-a-fake-dbcontext/

What are you hoping to achieve by testing the 3rd party tool? 您希望通过测试第三方工具实现什么? You could mock out the context var fakeContext = A.Fake<IDbContext>(); 您可以模拟上下文var fakeContext = A.Fake<IDbContext>(); and then assert that an attempt was made to write to the database. 然后断言试图写入数据库。 A.CallTo(() => fakeContext.SaveChanges()).MustHaveHappened();

The above example uses FakeItEasy mocking library. 上面的示例使用FakeItEasy模拟库。

The usual answer to these kinds of questions is: 这些问题的常见答案是:

  • Isolate the hard to test dependencies (the EF context) 隔离难以测试的依赖关系(EF上下文)
  • Provide a fake implementation in your tests to verify the correct behaviour of the SUT 在测试中提供伪造的实现,以验证SUT的正确行为

This all makes sense when you have interesting logic to test in your system under test. 当您有有趣的逻辑要在被测系统中进行测试时,所有这些都有意义。 For your specific case, the repository looks like a very thin abstraction between your clean domain and EF-aware logic. 对于您的特定情况,存储库看起来像是干净域和EF感知逻辑之间的非常薄的抽象。 Good, keep 'em that way. 很好,请保持这种方式。 This also means that it's not really doing much work. 这也意味着它并没有做太多工作。 I suggest that you don't bother writing isolated unit tests (wrapping EF DbContext seems like extra work that might not pull its weight). 我建议您不要费心编写隔离的单元测试(包装EF DbContext似乎是多余的工作,可能无法发挥作用)。

Note that I'm not saying you shouldn't test this code: I often tend to test these thin repositories using a real database, ie through integrated tests. 请注意,我并不是说您不应该测试此代码:我经常倾向于使用真实的数据库(即通过集成测试)来测试这些精简存储库。 For all the code that uses these repositories however, I'd stick to isolated unit testing by providing fake repositories to the system under test. 但是,对于所有使用这些存储库的代码,我都会通过向测试中的系统提供伪存储库来坚持隔离的单元测试。 That way I have coverage on my repository code and test that EF is actually talking to my database in the correct way and all other tests that indirectly use these repositories are nice, isolated and lightning-fast. 这样,我就可以覆盖我的存储库代码,并测试EF实际上是否以正确的方式与我的数据库进行通信,并且间接使用这些存储库的所有其他测试都很好,隔离且快如闪电。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM