如何使用Verify()方法仅验证某些属性?

The following will evalute to true if the method SendToTarget is getting called with a type of Message.

// Arrange
var osmMock = new Mock<OrderStateMachine>(MockBehavior.Strict, mapper, sessionId, repo);
osmMock.Setup(m => m.SendToTarget(It.IsAny<Message>())).Returns(true);
var osm = osmMock.Object;

// Act
// ...

// Assert
osmMock.Verify(m => m.SendToTarget(It.IsAny<Message>()), Times.Once);

但是,这是非常广泛的。

I would like to test that the method SendToTarget was called with an instance of Message having set a specific property to a specific value.

Sure I could pass an instance of Message to the method like this osmMock.Verify(m => m.SendToTarget(It.Is(myMessageInstance))). But I don't want to verfiy against a completely propagated instance of Message.

All I want is to verify that a specific property of the Message type is set to a specific value. I hope it's clear what I am trying to archive. How can this be done?

评论
  • 苍老师
    苍老师 回复

    添加另一个断言并检查属性?该消息是一个对象,通过引用传递,您可以达到顶峰。

  • cut
    cut 回复

    Try calling Verify with It.Is<Message>(Expression<Func<Message, bool>> match). Then you can check arbitrary conditions within that delegate, e.g. if you have a string property:

    osmMock.Verify(m => m.SendToTarget(It.Is<Message>(x => x.YourProperty == "some value")), Times.Once);