1

下面的代码片段最好地解释了我想要实现的目标:

[Test]
public void ReplayGoalTeamATest()
{
    var stateMachineMock = new Mock<IIceHockeyOddsStateMachine>();

    new IceHockeyActionLogRecord { Event = "goal", Team = "A"}.Replay(stateMachineMock.Object);

    stateMachineMock.Verify(s=>s.TeamAScore++); //Syntax error
}
4

3 回答 3

2

如果您的 IIceHockeyOddsStateMachine 接口上同时具有 getter 和 setter,则可以验证该值是否像这样递增:

var stateMachineMock = new Mock<IIceHockeyOddsStateMachine>();

stateMachineMock.SetupAllProperties();

stateMachineMock.Object.TeamAScore = 0;

new IceHockeyActionLogRecord { Event = "goal", Team = "A"}.Replay(stateMachineMock.Object);

Assert.That(stateMachineMock.Object.TeamAScore, Is.EqualTo(1));
于 2012-05-14T10:50:27.923 回答
1

当你这样做时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); 
于 2012-05-14T12:13:44.530 回答
0

您是否尝试过使用 .CallBack() 方法?不确定验证是否支持上述实现

于 2012-05-14T10:47:15.620 回答