質問

私はこのようなクラスを持っています:

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

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

しかしが良いコンストラクタでよく初期化されていても、それを割り当てることができません。私ものようなものを試してみてください

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メソッドのみのモック。

[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();
.

更新: こののような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);
.

他のヒント

MProduct.Behavior = MoleBehaviors.Fallthrough;
.
ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top