如何使用Moles作为构造函数?

Jec*_*eco 7 .net c# unit-testing mocking moles

我有一个这样的课:

public class Product : IProduct
{
    static private string _defaultName = "default";
    private string _name;
    private float _price;
    /// Constructor
    public Product()
    {
        _price = 10.0F;
    }
    public void ModifyPrice(float modifier)
    {
        _price = _price * modifier;
    }  
Run Code Online (Sandbox Code Playgroud)

我希望ModifyPrice不为特定值做任何事情,但我也想调用将价格设置为10的构造函数.我尝试过这样的事情:

var fake = new SProduct() { CallBase = true };
var mole = new MProduct(fake)
    {
        ModifyPriceSingle = (actual) =>
        {
            if (actual != 20.0f)
            {
                MolesContext.ExecuteWithoutMoles(() => fake.ModifyPrice(actual));
            }
        }
    };
MProduct.Constructor = (@this) => (@this) = fake;
Run Code Online (Sandbox Code Playgroud)

但即使使用良好的构造函数初始化,我也无法将其分配给@this.我也尝试过类似的东西

MProduct.Constructor = (@this) => { var mole = new MProduct(@this)... };
Run Code Online (Sandbox Code Playgroud)

但是这次我不能打电话给我的构造函数.我该怎么办?

Geb*_*ebb 5

您不需要模拟构造函数,类的无参数构造函数Product已经执行了您想要的操作.

添加一些调试输出到Product.

public class Product
{
    private float _price;
    public Product()
    {
        _price = 10.0F;
        Debug.WriteLine("Initializing price: {0}", _price);
    }
    public void ModifyPrice(float modifier)
    {
        _price = _price*modifier;
        Debug.WriteLine("New price: {0}", _price);
    }
}
Run Code Online (Sandbox Code Playgroud)

只模拟ModifyPrice方法.

[TestMethod]
[HostType("Moles")]
public void Test1()
{
    // Call a constructor that sets the price to 10.
    var fake = new SProduct { CallBase = true };
    var mole = new MProduct(fake)
    {
        ModifyPriceSingle = actual =>
        {
            if (actual != 20.0f)
            {
                MolesContext.ExecuteWithoutMoles(() => fake.ModifyPrice(actual));
            }
            else
            {
                Debug.WriteLine("Skipped setting price.");
            }
        }
    };
    fake.ModifyPrice(20f);
    fake.ModifyPrice(21f);
}
Run Code Online (Sandbox Code Playgroud)

请参阅调试输出以确认一切按预期工作:

    Initializing price: 10
    Skipped setting price.
    New price: 210

顺便说一句,你不需要在这里使用存根,

var fake = new SProduct { CallBase = true };
Run Code Online (Sandbox Code Playgroud)

创建一个Productwill 的实例就足够了.

var fake = new Product();
Run Code Online (Sandbox Code Playgroud)

更新: 使用AllInstances像这样的类可以实现模拟单个方法

MProduct.Behavior = MoleBehaviors.Fallthrough;
MProduct.AllInstances.ModifyPriceSingle = (p, actual) =>
{
    if (actual != 20.0f)
    {
        MolesContext.ExecuteWithoutMoles(() => p.ModifyPrice(actual));
    }
    else
    {
        Debug.WriteLine("Skipped setting price.");
    }
};

// Call the constructor that sets the price to 10.
Product p1 = new Product();
// Skip setting the price.
p1.ModifyPrice(20f);
// Set the price.
p1.ModifyPrice(21f);
Run Code Online (Sandbox Code Playgroud)