当你这样做时s.TeamAScore++
,你有两个不同的动作,你应该设置和验证。第一个动作是从您的依赖项中获取当前分数,第二个动作是设置新分数:
int score = stateMachine.TeamAScore;
// other staff
stateMachine.TeamAScore = score + 1;
所以,我会明确定义这种与依赖关系的交互:
// Arrange
Mock<IIceHockeyOddsStateMachine> stateMachineMock = new Mock<IIceHockeyOddsStateMachine>();
stateMachineMock.SetupGet(s => s.TeamAScore).Returns(0);
IceHockeyActionLogRecord record = new IceHockeyActionLogRecord { Event = "goal", Team = "A"};
// Act
record.Replay(stateMachineMock.Object);
// Assert
stateMachineMock.VerifySet(s => s.TeamAScore = 1);
在这种情况下,您正在测试 IceHockeyActionLogRecord,它与依赖项交互的方式。测试成为对象之间交互的规范。
当您验证 TeamAScore 值时,您正在测试模拟实现。Callback 的使用也将测试您的代码,而不是测试对象之间的交互。
另外,我会在您的测试中为幻数命名,甚至提供参数:
[TestCase(0, 1)]
[TestCase(50, 51)]
public void ShouldIncrementTeamScore(int initialScore, int expectedScore)
{
var stateMachineMock = new Mock<IIceHockeyOddsStateMachine>();
stateMachineMock.SetupGet(s => s.TeamAScore).Returns(initialScore);
IceHockeyActionLogRecord foo = new IceHockeyActionLogRecord();
foo.Replay(stateMachineMock.Object);
stateMachineMock.VerifySet(s => s.TeamAScore = expectedScore);
}
更新:如果您的界面没有属性 getter,那么只需修改 Arrange 部分测试(不要设置属性 getter 调用):
// Arrange
var stateMachineMock = new Mock<IIceHockeyOddsStateMachine>();
var record = new IceHockeyActionLogRecord { Event = "goal", Team = "A"};
// Act
record.Replay(stateMachineMock.Object);
// Assert
stateMachineMock.VerifySet(s => s.TeamAScore = 1);