使用依赖项注入时更改用于单元测试的假存储库
在我的程序中,我有一个可以简化为以下情况的情况:
- 一个 IRepository,我在其中创建一个 MemoryRepository 和一个 SqlRepository 实现
- 一个映射器,它注入 IRepository 构造函数。
- 包含我想要测试的业务逻辑的 Mapper.Map()
我创建了一个测试,其中 Mapper 接收 MemoryRepository。 通过在内存存储库上显式设置将在业务逻辑中使用的属性,我现在可以测试此逻辑。 但是,如果我使用注入,我将无法再访问该存储库。
一段代码可以告诉您比 1000 个普通单词更多的信息,这里是 Pastebin 链接。
你会怎么做呢?
In my program I have a situation that I can simplify to the following:
- An IRepository of which I create a MemoryRepository and a SqlRepository implementation
- A Mapper that gets the IRepository constructor injected.
- A Mapper.Map() that contains business logic I want to test
I created a test where the Mapper receives the MemoryRepository.
By explicitly setting a property on the memory repository that will be used in the business logic I can now test this logic.
If I use injection however, I wouldn't have access to this repository anymore.
A bit of code tells you more then a 1000 normal words, here is the pastebin link.
How would you go about this?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
如果我正确理解你的问题,基本上你担心你的存储库是在实例化测试类时创建并注入的,因此在你的测试方法中你无法修改存储库的状态,因为它已经在你的映射器中,当然,你的映射器不应暴露存储库的内部结构。
如果是这种情况,那么我认为您不必担心,只需修改 myMemoryCategoryRepository 的状态并执行映射器的方法即可。您的映射器应该采取相应的行为,因为您注入的是对存储库的引用,因此映射器内的对象与您要修改的对象相同。
If I understand your question correctly basically you are concerned that your repository was created AND injected when the test class was instantiated and so in your test method you cannot modify the state of your repository since it is already inside your mapper and, of course, your mapper should not expose the internals of the repository.
If that is the case then I don't think you have to worry, just modify the state of the myMemoryCategoryRepository and execute the mapper's method. Your mapper should behave accordingly because what you injected is a reference to the repository so the object inside the mapper is the same one as the one you would be modifying.
不完全确定您在这里问什么,您是在测试映射器还是存储库?如果您正在测试映射器,请伪造存储库。您已经做好了接缝,要么使用框架,要么在测试中手动创建一个假存储库,以便为了测试映射器而发出您想要的任何快乐的声音,并通过将假冒传递到构造函数来创建映射器。
因此,通过您自己的简化,
如果您需要验证存储库上的某些信息,请使用 Mock 而不是 Stub。
模拟和存根之间的区别
Not entirely sure what you're asking here, are you testing the mapper or the repository? If you're testing the mapper, then fake the repository. You've already got the seams in place, either use a framework or create a fake repository manually in your tests that makes whatever happy noises you want for the sake of testing Mapper and create the mapper by passing in your fake into the constructor.
So by your own simplification,
If you need to verify some information on the Repository, use a Mock rather than a Stub.
Difference Between Mocks and Stubs