C#-测试闭包
作者:互联网
我有一个非常简单的方法要测试. _interactionService会弹出一个对话框,询问用户有关删除客户的确认.如果在框中单击相应的按钮,则会调用提供的操作.该操作可操纵上下文并保存更改.保存完成后,将调用另一个操作.
private void Delete(object entity)
{
_interactionService.ShowConfirmationBox("Delete?", "Are you sure you want to delete this customer?", () =>
{
Customer customer = entity as Customer;
Context.Attach(customer);
Context.Delete(customer);
Context.Save(() => DoSomethingElseWhenSaveComplete);
});
}
我不知道如何测试这种方法.我嘲笑了服务和上下文,但是如何测试闭包?
解决方法:
如果上下文是模拟的,则可以在测试中使用callback:
Action saveAction = null;
contextMock
.Setup(c => c.Save(It.IsAny<Action>())
.Callback<Action>(a => saveAction = a);
// Call delete...
Assert.IsNotNull(saveAction);
saveAction();
// Assert that DoSomethingElseWhenSaveCompleted was done
标签:unit-testing,moq,c 来源: https://codeday.me/bug/20191201/2080855.html