且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

没有数据库的单元测试:Linq to SQL

更新时间:2023-02-08 18:01:21

Repository 的职责是持久化域对象并根据请求获取它们.即它的工作是获取一个对象并将其反序列化/序列化为某种形式的持久存储.

The Repository responsibility is to persist domain objects and fetch them on request. i.e. it's job is to take an object and deserialize/serialize it to from some form of durable storage.

因此对存储库的测试必须针对实际存储进行测试,在这种情况下是数据库.即这些是集成测试 - 测试您的类与外部数据库集成.

So tests for the repository have to test against the real storage in this case a DB. i.e. these are integration tests - tests that your class integrates with the external DB.

一旦你确定了这一点,客户端/应用程序的其余部分就不必针对真正的数据库工作了.他们可以模拟存储库并进行快速的单元测试.您可以假设自集成测试通过以来 GetAccount 工作正常.

Once you have this nailed, the rest of the client/app doesn't have to work against the real DB. They can mock the repository and have fast unit tests. You can assume that GetAccount works since the integration tests pass.

更多详情:通过将 Repository 对象作为 ctor 或方法 arg 传入,您为传入伪造或模拟打开了大门.因此,现在服务测试可以在没有真正存储库的情况下运行 >> 没有数据库访问 >> 快速测试.

More details: By passing in the Repository object as a ctor or method arg, you open the doors for passing in a fake or a mock. Thus now the service tests can run without a real repository >> there is no DB-access >> fast tests.

public void FreezeAllAccountsForUser(int userId, ILijosBankRepository accountRepository)
{
  // your code as before
}

test ()
{  var mockRepository = new Mock<ILijosBankRepository>();
    var service = // create object containing FreezeAllAccounts...

    service.FreezeAllAccounts(SOME_USER_ID, mockRepository);

    mock.Verify(r => r.GetAllAccountsForUser(SOME_USER_ID);
    mock.Verify(r => r.Update());
}