c# - 不使用 virtual 关键字的 Moq 具体类
问题描述
情况
我这里有以下代码
ITest.cs
public interface ITest
{
int Prop { get; }
int Calc();
}
测试.cs
public class Test : ITest
{
public int Prop { get; private set; }
public int Calc()
{
return Prop * 2;
}
}
我想测试这个Calc()
方法。如果我的理解是正确的,您不能在不使用virtual
关键字的情况下覆盖具体类的 getter 属性。
例如
var moq = new Mock<Test>(); // mocked Test class
moq.Setup(x => x.Prop).Returns(2); // throws an error,
// however with "virtual int Prop { get; }" it doesn't throw any exceptions
var moq = new Mock<ITest>(); // mocked ITest interface
moq.Setup(x => x.Prop).Returns(2); // works fine
// but can not really test the Calc() method (it returns 0
// because the proxy doesn't have Test's implementation)
问题
所以我的问题是:如何在Calc()
不制作的情况下测试virtual int Prop
顺便说一句...这也不起作用
var moq = new Mock<ITest>();
moq.Setup(x => x.Prop).Returns(2);
var obj = (Test)moq.Object; // can NOT convert ITestProxy to Test
解决方案
如果你想测试Calc()
然后测试Calc()
。你不需要嘲笑任何东西
[TestMethod]
public void Test_Calc_DoublesProp()
{
//arrange
var test = new Test(5); //assumes Prop value can be injected in constructor
//act
int result = test.Calc();
//assert
Assert.IsTrue(result == 10); // 5 * 2
}
推荐阅读
- server - VcXsrv WSL X 服务器意外关闭。我需要禁用 GPU 吗?
- laravel - 在 laravel eloquent 中获得多个结果而不是一个
- ghost-blog - Ghost博客有日志吗?
- port - 设置多路由器后,upnpc 映射到辅助路由器 ip 而不是外部 ip
- javascript - 我们需要 RXJS combineLatest 和 ActivateRouted.pathFromRoot 吗?
- algorithm - 什么是最小最优+证明的这个问题的贪心算法?
- r - 如何在 R 中对数据进行分组以对每个团队进行总计?
- firebase - 我是否需要在 firebase 云函数中的 context.auth 对象上使用 verifyIdToken?
- python - 基于子集重新分配数据集中的值
- java - 从另一个 Activity 类执行 Fragment 中的 AsyncTask 并更新其中的 UI