如何在存储库模式中对代码进行单元测试? [英] How to unit test code in the repository pattern?

查看:46
本文介绍了如何在存储库模式中对代码进行单元测试?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何测试这种情况:

我有一个用户存储库(到目前为止)只有一种方法: SaveUser .
可以设置"SaveUser"来接收用户作为参数,并使用EF 6将其保存到DB.
如果用户是新用户(新用户由数据库中不存在的电子邮件"定义),则该方法应插入该用户,否则,该方法应仅更新它.
从技术上讲,如果调用此方法,则所有业务验证都可以,仅保留实际保留用户的行为

I have a user repository that (so far) only has one method: SaveUser.
"SaveUser" is suposed to receive a user as a parameter and save it to the DB using EF 6.
If the user is new (new user is defined by a "Email" that is not present in the database) the method is supposed to insert it, if its not, the method is supposed to only update it.
Technically if this method is called, all business validation are OK, only remaining the act of actually persisting the user

我的问题是:我实际上不想创建一个新用户或每次更新一个用户...这将在将来导致不希望出现的副作用(我们称其为纸迹")...如何我会这样做吗?

My problem here is: I don't actually want to create a new user or update one every time... this would lead to undesired side effects in the future (let's call it "paper trail")... How do i do it?

这是测试代码:

public void CreateOrUpdateUserTest1()
    {
        UserDTO dto = new UserDTO();
        dto.UniqueId = new Guid("76BCB16B-4AD6-416B-BEF6-388D56217E76");
        dto.Name = "CreateOrUpdateUserTest1";
        dto.Email = "leo@leo.com";
        dto.Created = DateTime.Now;
        GeneralRepository repository = new GeneralRepository();
        //Now the user should be CREATED on the DB
        repository.SaveUser(dto);

        dto.Name = "CreateOrUpdateUserTest";
        //Now the user should be UPDATED on the DB
        repository.SaveUser(dto);
    }

推荐答案

您的存储库可能需要调用第三方库的某些方法来实际保留数据.在这种情况下,单元测试只有在您可以模拟第三方库并验证并且存储库正确调用了特定的持久性方法后才有意义.为此,您需要重构代码.

Your repository probably needs to invoke some methods of a third party library to actually persist the data. Unit-testing in such case could only make sense if you could mock the third party library and verify and the particular persistence methods are being correctly invoked by your repository. To achieve this, you need to refactor your code.

否则,您不能对此类进行单元测试,但也请考虑可能不需要这样做.负责持久性的第三方库是一个不同的组件,因此测试数据库存储是否可以正确地与您的类一起工作是

Otherwise, you can't unit-test this class, but also consider that maybe there is no need to. The third party library responsible for persistence is a different component, so testing if DB storage works correctly with your classes is rather a matter of Integration testing.

这篇关于如何在存储库模式中对代码进行单元测试?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆