0

我正在使用 AAA 模式和 Rhino 模拟进行单元测试。在调用 DbContext 上的 SaveChanges() 之前,我想断言已在实体上设置了特定值(电子邮件)。我有一个看起来像这样的测试方法:

protected override void Arrange()
{
    base.Arrange();
    _itemToUpdate = new FooEntity();
}

protected override void Act()
{
    base.Act();
    _resultEntity = Repository.Update(_itemToUpdate);
}

[TestMethod]
public void ShouldAssignEmailBeforeSave() // Act
{
   Context.AssertWasCalled(x => x.SaveChanges(), 
      options => options.WhenCalled(y => 
         Assert.IsTrue(_resultEntity.Email == "somevalue")));
}

但我意识到“WhenCalled”方法没有执行,因为我也试过这个:

[TestMethod]
public void ShouldAssignEmailBeforeSave()
{
    Context.Expect(x => x.SaveChanges())
       .WhenCalled(y => Assert.IsTrue(false));
}

我也尝试过这种语法:

[TestMethod]
public void ShouldAssignEmailBeforeSave()
{
    Context.AssertWasCalled(x => x.SaveChanges(),
       options => options.WhenCalled(z => Assert.IsTrue(false)));
}

上面的两个断言都通过了,这很明显我没有WhenCalled正确使用。Context是我的 DBSet 的一个模拟对象。我暂时将安排和法案放在了问题之外,因为他们似乎做了他们应该做的事情。是断言不起作用。

如何在调用方法之前验证是否在实体上设置了属性?换句话说,我如何断言某件事是按特定顺序发生的?

  1. 设置属性。
  2. 保存更改。

编辑:

发生“错误”是因为 Assert 是在 Act 之后完成的,这是正确的。不可能WhenCalled在 Assert 中使用,因为 Act 已经发生。在这种特殊情况下,永远不会调用 WhenCalled,因为委托是在SaveChanges调用之后创建的,因此在调用时不存在。

另一种方法是Expect在 Arrange 中使用:

protected override void Arrange()
{
    base.Arrange();
    _itemToUpdate = new FooEntity();
    Context.Expect(x => x.SaveChanges()).Return(0).WhenCalled(y =>
    {
        Assert.IsTrue(false);
    });
}

[TestMethod]
public void ShouldCallSaveChanges()
{
    Context.VerifyAllExpectations();
}

但是你在安排中有一个断言,我认为这违背了 AAA 模式的最佳实践。有更好的解决方案的想法吗?

4

2 回答 2

0

看来您正在寻找的是验证模拟调用的顺序。这可能是MockRepository.Ordered()3.5 版的方法,但不是 3.6 语法的一部分。
您可以在此处此处查看可能的解决方案。这对于 AAA 来说可能是最简单的:

Context.AssertWasCalled(x => _resultEntity.Email = "somevalue", options => options.WhenCalled(w => Context.AssertWasNotCalled(x=>x.SaveChanges())));
Context.AssertWasCalled(x=>x.SaveChanges());
于 2016-02-08T13:25:01.190 回答
0

我最终得到了这个:

private FooEntity _itemToUpdate;
private FooEntity _resultEntity;

protected override void Arrange()
{
    base.Arrange();
    var correctValue = "somevalue"
    _itemToUpdate = new FooEntity()
    _itemToUpdate.Email = correctValue;

    // Context is a mock of a DbContext and inherited from base class.
    Context.Expect(x => x.SaveChanges()).Return(0).WhenCalled(y =>
    {
        Assert.AreEqual(_resultEntity.Email, correctValue);
    });
    Context.Replay();
}

protected override void Act()
{
    base.Act();
    // Repository is a mock of a repository and inherited from base class.
    _resultEntity = Repository.Update(_itemToUpdate);
}

[TestMethod]
public void ShouldAssignEmailBeforeSave() // Assert
{
   Context.VerifyAllExpectations();
}

由于实体不是模拟 AssertWasCalled 将不起作用。

于 2016-02-08T14:20:37.103 回答