在原始问题中提供的所示代码示例中没有什么可以模拟的。
此外,在单独进行单元测试时,通常不会模拟被测主题 (SUT)
以下面的类为例
public class FloorManager {
private List<FloorInfo> floors;
public FloorManager() {
floors = new List<FloorInfo>();
}
public IEnumerable<FloorInfo> Floors => floors;
public FloorInfo FindFloorByName(string name) {
FloorInfo fInfo = floors.Find(floor => floor.Name == name);
return fInfo;
}
public void Add(FloorInfo floor) {
floors.Add(floor);
}
}
public class FloorInfo {
public String Name { get; set; }
}
对面向公众的学科类成员的一些简单测试
[TestClass]
public class FloorManagerTests {
[TestMethod]
public void Should_Create_Default_FloorManager() {
//Arrange
FloorManager subject = null;
//Act
subject = new FloorManager();
//Assert - FluentAssertions
subject.Should().NotBeNull();
subject.Floors.Should()
.NotBeNull()
.And.HaveCount(0);
}
[TestMethod]
public void Should_Add_Floor() {
//Arrange
string floorName = "First Floor";
var floor = new FloorInfo { Name = floorName };
var subject = new FloorManager();
//Act
subject.Add(floor);
//Assert - FluentAssertions
subject.Floors.Should().HaveCount(1);
}
[TestMethod]
public void Should_FindFloorByName() {
//Arrange
string expected = "First Floor";
var floor = new FloorInfo { Name = expected };
var subject = new FloorManager();
subject.Add(floor);
//Act
FloorInfo actual = subject.FindFloorByName(expected);
//Assert - FluentAssertions
actual.Should().NotBeNull();
actual.Name.Should().Be(expected);
}
}
随着主题类的复杂性增加,可以添加更多测试来验证预期行为。
如果经理改为依赖于服务
例如,
public class FloorManager {
private IFloorCollection floors;
public FloorManager(IFloorCollection floors) {
this.floors = floors;
}
public IEnumerable<FloorInfo> Floors => floors.All;
public FloorInfo FindFloorByName(string name) {
FloorInfo fInfo = floors.Find(floor => floor.Name == name);
return fInfo;
}
public void Add(FloorInfo floor) {
floors.Add(floor);
}
}
public interface IFloorCollection {
IEnumerable<FloorInfo> All { get; }
void Add(FloorInfo floor);
FloorInfo Find(Func<FloorInfo, bool> p);
}
public class FloorInfo {
public String Name { get; set; }
}
然后需要模拟依赖关系以便单独测试主题。
[TestMethod]
public void Should_FindFloorByName() {
using (var mock = AutoMock.GetLoose()) {
//Arrange
string expected = "First Floor";
var floor = new FloorInfo { Name = expected };
FloorManager subject = mock.Create<FloorManager>();
mock.Mock<IFloorCollection>()
.Setup(_ => _.Find(It.Is<Func<FloorInfo, bool>>(f => f(floor))))
.Returns(floor);
//Act
FloorInfo actual = subject.FindFloorByName(expected);
//Assert - FluentAssertions
actual.Should().NotBeNull();
actual.Name.Should().Be(expected);
}
}