我正在与 Moles 一起编写一些单元测试。我在网上搜索过,但没有看到任何关于如何使用 Moles 拦截对 AppSettingsReader.GetValue 的调用的回复。
有没有人能够使用 Moles 做到这一点?或者我是否被迫隔离自己班级中可以注入或模拟的调用?理想情况下,有一种方法可以直接使用 Moles 来拦截调用,因为我们真的不想修改要测试的代码。
谢谢!
首先,我强烈建议迁移到 .NET 4.5 / C# 5 / Visual Studio 2012 中的 Moles 发布版本,称为“Fakes and Stubs”。
System.Configurations 命名空间与 Mole/Fake 类型不兼容,必须被存根。要使用 Moles 框架创建存根,只需为 System.Configuration.AppSettingsReader 类型创建一个接口。Moles 编译器会自动将接口转换为 Stub 类型。
这是您可以添加到项目中的界面:
using System;
namespace YOUR_NAMESPACE_HERE
{
/// <summary>
/// IOC object for stubbing System.Configuration.AppSettingsReader.
/// Provides a method for reading values of a particular type from
/// the configuration.
/// </summary>
interface IAppSettingsReader
{
/// <summary>
/// Gets the value for a specified key from the
/// System.Configuration.ConfigurationSettings.AppSettings property
/// and returns an object of the specified type containing the
/// value from the configuration.
/// </summary>
/// <param name="key">The key for which to get the value.</param>
/// <param name="type">The type of the object to return.</param>
/// <returns>The value of the specified key</returns>
/// <exception cref="System.ArgumentNullException">key is null.
/// - or -
/// type is null.</exception>
/// <exception cref="System.InvalidOperationException">key does
/// not exist in the <appSettings> configuration section.
/// - or -
/// The value in the <appSettings> configuration section
/// for key is not of type type.</exception>
public object GetValue(string key, Type type);
}
}
这也是一个存根类:
using System;
using System.Configuration;
namespace YOUR_NAMESPACE_HERE
{
/// <summary>
/// Production stub for System.Configuration.AppSettingsReader.
/// Provides a method for reading values of a particular type from
/// the configuration.
/// </summary>
public class AppSettingsReaderStub : IAppSettingsReader
{
/// <summary>
/// Gets the value for a specified key from the
/// System.Configuration.ConfigurationSettings.AppSettings property
/// and returns an object of the specified type containing the value
/// from the configuration.
/// </summary>
/// <param name="key">The key for which to get the value.</param>
/// <param name="type">The type of the object to return.</param>
/// <returns>The value of the specified key</returns>
/// <exception cref="System.ArgumentNullException">key is null.
/// - or -
/// type is null.</exception>
/// <exception cref="System.InvalidOperationException">key does not
/// exist in the <appSettings> configuration section.
/// - or -
/// The value in the <appSettings> configuration section for
/// key is not of type type.</exception>
public object GetValue(string key, Type type)
{
var reader = new AppSettingsReader();
object result = reader.GetValue(key, type);
return result;
}
}
}