背景
- 替换方法|函数|属性,范围涉及默认|全部|全不|定向。
代码
using Moq;
using System.Data;
using System.Diagnostics;
using Xunit;
namespace CallBack
{
public class Builder
{
// 交互(方法)
public virtual void Interact(string content)
{
Debug.Print(content);
}
// 数据(函数)
public virtual DataTable GetData()
{
var result = new DataTable();
result.Columns.Add("id", typeof(int));
result.Rows.Add(1);
return result;
}
}
public class BuilderTests
{
private const int
realTableRows = 1,
mockTableRows = 2;
// 默认CallBase = false
private Mock<Builder> mock = new Mock<Builder>();
[Fact(DisplayName = "默认")]
public void ExecuteDefault_ReturnsNull()
{
mock.Object.Interact("default");
var actual = mock.Object.GetData();
Assert.Null(actual);
}
[Fact(DisplayName = "全不重写")]
public void NotOverride_ReturnsTrue()
{
mock.CallBase = true;
mock.Object.Interact("default"); // 打印default
int count = mock.Object.GetData().Rows.Count;
Assert.True(count == realTableRows);
}
[Fact(DisplayName = "全重写")]
public void OverrideAll_ReturnsTrue()
{
mock.Setup(x => x.Interact(It.IsAny<string>())); // 空方法,效果同省略
mock.Setup(x => x.GetData()).Returns(FakeTable);
mock.Object.Interact("default"); // 不打印
int count = mock.Object.GetData().Rows.Count;
Assert.True(count == mockTableRows);
}
[Fact(DisplayName = "定向重写")]
public void Specify_ReturnsTrue()
{
mock.CallBase = true; // 先采用基类方法和函数
mock.Setup(x => x.Interact(It.IsAny<string>())); // 再定向重写
mock.Object.Interact("default"); // 不打印
int count = mock.Object.GetData().Rows.Count;
Assert.True(count == realTableRows);
}
private DataTable FakeTable()
{
var result = new DataTable();
result.Columns.Add("id", typeof(int));
result.Rows.Add(1);
result.Rows.Add(2);
return result;
}
}
}
网友评论