I'm new to Moq. I'm mocking a PagingOptions
class. Here is how the class looks like:
public class PagingOptions
{
[Range(1, 99999, ErrorMessage = "Offset must be greater than 0.")]
public int? Offset { get; set; }
[Range(1, 100, ErrorMessage = "Limit must be greater than 0 and less than 100.")]
public int? Limit { get; set; }
public PagingOptions Replace(PagingOptions newer)
{
return new PagingOptions
{
Offset = newer.Offset ?? Offset,
Limit = newer.Limit ?? Limit
};
}
}
Here is my mock version of the class,
var mockPagingOptions = new Mock<PagingOptions>();
mockPagingOptions.Setup(po => po.Limit).Returns(25);
mockPagingOptions.Setup(po => po.Offset).Returns(0);
I get the below error when setting up the property values. Am I making something wrong. Looks like I cannot Moq concrete class? Only Interfaces can be Mocked? Please assist.
Thanks, Abdul
ベストアンサー1
Moq creates an implementation of the mocked type. If the type is an interface, it creates a class that implements the interface. If the type is a class, it creates an inherited class, and the members of that inherited class call the base class. But in order to do that it has to override the members. If a class has members that can't be overridden (they aren't virtual, abstract) then Moq can't override them to add its own behaviors.
この場合、PagingOptions
本物のものを使用する方が簡単なので、モックする必要はありません。代わりに次のようになります。
var mockPagingOptions = new Mock<PagingOptions>();
mockPagingOptions.Setup(po => po.Limit).Returns(25);
mockPagingOptions.Setup(po => po.Offset).Returns(0);
これを行う:
var pagingOptions = new PagingOptions { Limit = 25, Offset = 0 };
何かをモックするかどうかをどのように決定しますか? 一般的に、具体的なランタイム実装をテストに含めたくない場合は、何かをモックします。 両方のクラスを同時にテストするのではなく、1 つのクラスをテストします。
しかし、この場合は、PagingOptions
単にデータを保持するクラスです。モック化しても意味がありません。本物を使うのも同じくらい簡単です。