单元测试与基类交互的方法 [英] Approach to unit testing interaction with a base class
问题描述
似乎有三种一般模式可用于测试派生类与其基础 1 的交互方式。由于我在下面列出的原因,我真的不喜欢它们中的任何一个。有没有人用这些(或另一种)测试基类交互的方法取得长期成功?
There seems to be three general patterns for testing the way a derived class interacts with it's base1. I don't really like any of them, for the reasons I've listed below. Has anyone had long term success with one of these (or another) methods for testing base class interaction?
- 更改访问修饰符允许
朋友
(C#中的内部
)访问并设置InternalsVisibleTo
包含模拟框架/单元测试程序集
- Change the access modifiers to allow
Friend
(internal
in C#) access and setInternalsVisibleTo
to include the mocking framework / unit test assembly
更改SUT以允许进行测试是测试气味。如果方法是受保护的
,那么它是受保护的
,因为这是适当的设计(我实际上还没看到我的内容)会调用受保护的朋友
(受保护的内部
)的有效使用。)
Changing the SUT to allow for testing is a test smell. If the method is Protected
, it's Protected
because that's the appropriate design for it (I actually have yet to see what I would call a "valid" use of Protected Friend
(protected internal
)).
- 使用反射和扩展方法创建你想要模拟的方法的可访问版本...然后模拟它
- Use reflection and an extension method to create an accessible version of the method you want to mock... then mock it
这需要大量额外的工作来模拟单个方法,它不是完全类型安全的(例如重命名会杀死它),并且(至少在VB中)需要创建模块
将方法放入,这是一个设计噩梦(模块不能进入类内部,因此它们需要在最受限制的情况下 Friend
,而且你的泛型是更复杂)!
This requires a lot of extra work to mock a single method, it's not completely type-safe (e.g. a rename would kill it), and (at least in VB), requires creating a Module
to put the method in to, which is a design nightmare (modules cannot go inside classes, so they need to be Friend
at the most restricted, and you generics are more complicated)!
- 使用状态测试代替行为测试。
根据基类的复杂程度,这可能需要很多更多的测试,而不是单个行为测试。考虑状态测试中需要什么来匹配 Me.AssertWasCalled(函数s.SendMessage(messageText,[to]))
其中 SendMessage
是基类受保护的
方法。
Depending on how complex the base class is, this can require a lot more tests than a single behavior test for the same thing. Consider what would be required in state testing to match a Me.AssertWasCalled(Function(s) s.SendMessage(messageText, [to]))
where SendMessage
is a base class Protected
method.
1 注意:在Moq中,这不是必需的,它通过 String
方法的名称支持模拟受保护的方法。正如Ayende在上面的链接中提到的,他特别避免了在Rhino Mocks中的任何非编译时类型安全模拟(我认为这是一件好事!)
1NOTE: This is not necessary in Moq which supports mocking protected methods via String
names of the method. As Ayende mentions in the link above, he specifically avoided any non compile-time type safe mocking in Rhino Mocks (which I think is a good thing!)
推荐答案
只是我的拙见。
通常,测试与基类的交互并不是一个好主意。正如您将在此处测试实现细节。
Generaly it is not a good idea to test interactions with base class. As you are going to test implementation details here.
如果使用基类测试继承的类togehter似乎很复杂,那么可能是时候了重构和使用聚合而不是继承?
If testing inherited class togehter with base class seems to be complicated then it is probably time to refactor and use aggregation instead of inheritance?
这篇关于单元测试与基类交互的方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!