Can you help me understand Moq Callback?

前端 未结 5 882
傲寒
傲寒 2020-12-09 00:24

Using Moq and looked at Callback but I have not been able to find a simple example to understand how to use it.

Do you have a small working snippet whic

5条回答
  •  半阙折子戏
    2020-12-09 01:17

    Here's an example of using a callback to test an entity sent to a Data Service that handles an insert.

    var mock = new Mock();
    DataEntity insertedEntity = null;
    
    mock.Setup(x => x.Insert(It.IsAny())).Returns(1) 
               .Callback((DataEntity de) => insertedEntity = de);
    

    Alternative generic method syntax:

    mock.Setup(x => x.Insert(It.IsAny())).Returns(1) 
               .Callback(de => insertedEntity = de);
    

    Then you can test something like

    Assert.AreEqual("test", insertedEntity.Description, "Wrong Description");
    

提交回复
热议问题