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

2024-04-22

我有一堂这样的课:

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;
    }  

I want 修改价格对特定值不执行任何操作,但我还想调用将价格设置为 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;

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

MProduct.Constructor = (@this) => { var mole = new MProduct(@this)... };

但这次我无法调用我的构造函数。我该怎么办?


你不需要模拟构造函数,无参构造函数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);
    }
}

仅模拟ModifyPrice method.

[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);
}

查看调试输出以确认一切按预期工作:



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

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

var fake = new SProduct { CallBase = true };

创建一个实例Product就足够了。

var fake = new Product();

Update:模拟单个方法可以通过以下方式实现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);
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

如何使用 Moles 作为构造函数? 的相关文章

随机推荐