验证在单元测试中是否调用了一种方法 [英] Verify that either one method or the other was invoked in a unit test

查看:278
本文介绍了验证在单元测试中是否调用了一种方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

示例:

public bool Save(MyObj instance)
{
    if (instance.IsNew)
    {
        this.repository.Create(instance);
    }
    else
    {
        this.repository.Update(instance);
    }
}

如何在Moq中创建测试以验证:

How do I create a test in Moq that verifies:

  1. 正在读取属性IsNew
  2. 已调用Create()Update()
  1. that a property IsNew is being read
  2. that either Create() or Update() has been invoked

推荐答案

不幸的是,我自己有解决方案.

Unfortunately I have a solution myself.

您要做的就是拥有一个设置为0的局部int变量,然后通过模拟对其进行递增.最后,您必须检查其名称是否大于0(或完全1,具体取决于问题).

All you have to do is to have a local int variable that you set to 0 and then mocking increments it. In the end you have to check whether its name is more than 0 (or exactly 1, depending on the problem).

// Arrange
int count = 0;
Mock<Repository> mock = new Mock<Repository>();
mock.Setup<bool>(m => m.Create(It.IsAny<MyObj>())).Callback(() => count++);
mock.Setup<bool>(m => m.Update(It.IsAny<MyObj>())).Callback(() => count++);
// Act
...
// Assert
Assert.AreEqual(count, 1);

将进行两次测试.一种将属性IsNew设置为true,另一种将其设置为false.

There would be two tests. One that sets property IsNew to true and one that sets it to false.

这篇关于验证在单元测试中是否调用了一种方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆