如何提供 Seam 的干净实现
在许多情况下,我使用受保护的虚拟方法编写代码以提供接缝(以协助单元测试):
public class TemporaryStorage
{
public TemporaryStorage()
{
this.RootPath = Path.Combine(this.GetEnvironmentPath, Path.GetRandomFileName());
}
public string RootPath { get; private set; }
protected virtual string GetEnvironmentPath
{
get { return LocalStorage.GetEnvironmentPath(); }
}
}
然后,在测试套件中,我将从此类派生并为 GetEnvironmentPath() 提供自定义实现。
除了在测试套件中创建派生类之外,是否有更好的方法可用?我可以使用 MOQ 来实现相同的结果(为 GetEnvironmentPath 提供替代实现)吗?
问候,
In many cases, I write code with protected virtual methods to provide seams (to assist in unit testing):
public class TemporaryStorage
{
public TemporaryStorage()
{
this.RootPath = Path.Combine(this.GetEnvironmentPath, Path.GetRandomFileName());
}
public string RootPath { get; private set; }
protected virtual string GetEnvironmentPath
{
get { return LocalStorage.GetEnvironmentPath(); }
}
}
Then, in the test suite, I will derive from this class and provide a custom implementation for GetEnvironmentPath().
Instead of creating the derived class within the test suite, is a better approach available? Can I use MOQ to accomplish the same results (providing a substitue implementation for GetEnvironmentPath)?
Regards,
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
模拟被测类的最简单方法是使用接口。当您的被测类实现某个接口时,您可以简单地使用 MOQ 编写一个模拟,如下所示:
比方说,您有一个这样的接口:
然后您可以像这样配置一个模拟:
您可以在中访问您的模拟对象你的单元测试是这样的:
The easiest way to mock your classes under test is using interfaces. When your class under test implements a certain interface, then you can simply write a mock using MOQ like this:
Let's say, you've got an interface like that:
Then you can configure a mock like this:
You can access your mocked object in your unit test in this way:
Rhino Mocks 是支持此功能的模拟框架之一。
如果您查看以下信息,您会看到
为了确保受保护的方法可以进行单元测试,您可以将签名更改为内部受保护而不是受保护。如果您随后在 AssemblyInfo.cs 中使用 InternalsVisibleTo,则可以使内部结构对单元测试项目可见(请参阅 如何使用 RhinoMocks 使“受保护”方法可用于“部分”模拟)。
Rhino Mocks is one of the mocking frameworks that supports this.
If you have a look at the following info you see an example.
To make sure that the protected method can be unit tested you can change the signature to internal protected instead of protected. If you then use the InternalsVisibleTo in your AssemblyInfo.cs you can make your internals visible to the unit testing project (see How to make a "protected" method available for "partial" mocking using RhinoMocks).