A more gentle introduction of Seams into the application could be achieved by making core methods virtual. This means that you would be able to use the Extract and Override technique for unit testing.
In greenfield development I find this technique suboptimal because there are better alternatives available, but it's a good way to retrofit testability to already existing code.
As an example, you write that your Specification hits the database. Within that implementaiton, you could extract that part of the specification to a Factory Method that you can then override in your unit tests.
如果您不想对工厂进行构造函数注入,并且不想使规范可模拟...您考虑过 TypeMock 吗?对于处理这种事情来说,它是非常强大的。您可以告诉它模拟要创建的下一个类型 X 的对象,并且它可以模拟任何内容,不需要虚拟等。
If you dont want to do constructor injection of a factory, and make the specs mockable... Have you considered TypeMock? It is very powerful for dealing with this sort of thing. You can tell it to mock the next object of type X that is to be created, and it can mock anything, no virtuals etc required.
发布评论
评论(4)
通过将核心方法设为
虚拟
,可以将Seams更温和地引入应用程序。这意味着您将能够使用提取和覆盖技术进行单元测试。在绿地开发中,我发现这种技术不是最理想的,因为有更好的替代方案可用,但它是对现有代码进行可测试性改造的好方法。
例如,您写道您的规范已命中数据库。在该实现中,您可以将规范的该部分提取到 工厂方法,然后您可以覆盖它在你的单元测试中。
总的来说,《有效处理旧代码》一书提供了很多关于如何使代码可测试。
A more gentle introduction of Seams into the application could be achieved by making core methods
virtual
. This means that you would be able to use the Extract and Override technique for unit testing.In greenfield development I find this technique suboptimal because there are better alternatives available, but it's a good way to retrofit testability to already existing code.
As an example, you write that your Specification hits the database. Within that implementaiton, you could extract that part of the specification to a Factory Method that you can then override in your unit tests.
In general, the book Working Effectively with Legacy Code provides much valuable guidance on how to make code testable.
如果您不想对工厂进行构造函数注入,并且不想使规范可模拟...您考虑过 TypeMock 吗?对于处理这种事情来说,它是非常强大的。您可以告诉它模拟要创建的下一个类型 X 的对象,并且它可以模拟任何内容,不需要虚拟等。
If you dont want to do constructor injection of a factory, and make the specs mockable... Have you considered TypeMock? It is very powerful for dealing with this sort of thing. You can tell it to mock the next object of type X that is to be created, and it can mock anything, no virtuals etc required.
您可以将
getDuplicateUsernameSpecification()
提取到其自己的公共方法中,然后子类化并覆盖该方法以进行测试。You could extract
getDuplicateUsernameSpecification()
into a public method of its own, then subclass and override that for your tests.如果您使用 IoC,那么您可以解析 DuplicateUsernameSpecification 并在测试模型中解决最后一个
编辑:这个想法是用工厂方法替换直接构造函数调用。像这样的事情:
If you use IoC then you can resolve the DuplicateUsernameSpecification and in test mockup the last one
Edit: The idea is to replace direct constructor call with factory method. Something like this: