我正在和Moles一起写一些单元测试。我在网上搜索了一下,但我没有看到任何关于如何使用Moles截获对AppSettingsReader.GetValue的呼叫的回应。
有没有人能用Moles做到这一点?或者我被迫在我自己的类中隔离我可以注入或模拟的调用?理想情况下,有一种方法可以直接使用Moles来拦截调用,因为我们并不真的想修改要测试的代码。
谢谢!
发布于 2012-08-01 04:13:23
首先,我强烈推荐在Visual Studio4.5/ C# 5/ .NET Studio2012中使用Moles的发行版,称为“伪和存根”。
System.Configurations命名空间与Mole/Fake类型不兼容,必须存根。要使用Moles Framework创建存根,只需为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;
}
}
}https://stackoverflow.com/questions/11720687
复制相似问题