:C# Mock a Class With an Internal Property Setter部品番号とモック方法とmoq.Objectを利用できるようにするには
ここで私が持っているものの要約。
私はInterface
を次ています
public interface IPosition
{
// Some properties here which must be accessed in CalcValueChangeAtDate method.
int Size { get; }
...
double CalcValueChangeAtDate(DateTime fromDate, DateTime toDate);
}
そして、私はこのようなクラスRealPosition
にインターフェイスを実装:
IPosition
インタフェースを使用して別のクラスを作成しさらに
public class RealPosition : IPosition
{
/* IPosition implementation */
public double CalcValueChangeAtDate(DateTime fromDate, DateTime toDate)
{
return CalcValueChangeAtDate(this, fromDate, toDate);
}
/* I created this static method with the idea to use the for mocked objects.
* This way I would need to implement the logic only once and use it with real
* and mocked objects*/
public static double CalcValueChangeAtDate(IPosition pos, DateTime fromDate, DateTime toDate)
{
// Logic here must access properties of IPosition
}
}
私のテストセットアップは次のようになります。
[Test]
public void RecalcOriginalEquityCurve()
{
// Here I get a list of mocked IPositions
List<IPosition> Positions = ImporterTools.GetPositions(FilePath, FullPositionsCsv);
// Execute Test
DataSeries equityCurve = EquityCurveBuilder.BuildEquityCurve(Positions);
// Evaluate test results
...
}
public class ImporterTools
{
public static List<IPosition> GetPositions(string path, string fileName)
{
// Import raw data and create a mocked IPosition
Mock<IPosition> tmpPosMoq = new Mock<IPosition>();
tmpPosMoq.Setup(v => v.CalcValueChangeAtDate(It.IsAny<DateTime>(), It.IsAny<DateTime>())).
Returns(???);
// Create a List and return it
}
}
問題は、ユニットテストではすべて私が嘲笑している位置です。しかし、CalcEquityCurve()
メソッドは、IPostion
のCalcValueChangeAtDate()
を呼び出します。 CalcEquityCurve()
を正しくテストするには、CalcValueChangeAtDate()
が有効な値を返す必要があります。戻り値は、メソッドの引数に依存します。従って、模擬オブジェクトがstatic
メソッドRealPosition.CalcValueChangeAtDate()
を呼び出すという考え方。
今、私は???
で立ち往生しています。
tmpPosMoq.Object.CalcValueChangeAtDate(fromDate, toDate);
はそれが可能ですべてです:私は単に私が呼ぶときRealPosition
クラスからの私static
メソッドが呼び出されるように、そこに書き込むためにどのような任意のアイデアを持っていませんか?
ありがとうございました!
tmpPosMoq.Setup(v => v.CalcValueChangeAtDate(It.IsAny<DateTime>(), It.IsAny<DateTime>())).
Returns((DateTime dtfrom, DateTime dtto) =>
{
return RealPosition.CalcValueChangeAtDate(tmpPosMoq.Object, dtfrom, dtto);
});
をしかし、これは完全に無意味です: コンスタンチン
あなたのコメントで 'CalcValueChangeAtDate'を判断すると、あなたはモックのポイントを見逃していると思います。モックを可能な限り単純なものに戻すことができるようにしてください。これは、使用しているものが何であっても知ることができます。この場合は、「ダブル」のような魔法の数字になります。 '1.2345'のようなものを返し、テスト中のシステムがその値を取得していることを確認します。 –
実際の実装を呼び出す場合は、何かを模倣しないでください。あなたの目標がモックのためにどうなっているかは非常に不明です。 – Crowcoder
@Crowcoder: 入力いただきありがとうございます。私は説明を変更し、今私の目標が明確になることを願っています。 – Konstantin