验证MOQ单元测试方法的返回值 [英] validate MOQ unit test method return value

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

问题描述

我有使用Moq编写的下面的类和测试类:

I have the below class and test class written using Moq:

public class Mytest : testin
{
    public int getId(int id)
    {
      int s = 2;
      return s;
    }

}

测试班:

private Mock<testin> _mock;

[TestInitialize]
public void Setup()
{
    _mock = new Mock<testin>();

}

[TestMethod]
public void returngetId()
{

    // Build up our mock object

    _mock.Setup(x => x.getId(It.IsAny<int>())).Returns(1)

}

我要从函数中返回 2 ,并在单元测试用例中检查值 1 .根据我的理解,测试用例应该失败.但即时通讯收到成功消息.我如何验证返回值正是我所期望的?如果返回的不是1,我想通过测试.

I'm returning 2 from the function and in unit test cases checking for the value 1. As per my understanding the test cases should fail. But im getting success message. How i can validate the return value is exactly what im expecting? I want to fail the test if it returning other than 1.

推荐答案

您当前的设置将跳过该方法的执行,而是盲目地"返回1.如果希望执行该方法,则不应模拟该方法.如果删除设置行,则测试用例确实会失败.通常,仅在不需要执行该方法时,才应模拟该方法.

Your current setup will skip the method's execution, and instead "blindly" return 1. You should not mock the method if you wish it to be executed. If you remove the setup line, your test cases will indeed fail. In general, you should only mock a method if you need it to NOT be executed.

要澄清:

_mock.Setup(x => x.getId(It.IsAny<int>())).Returns(1)行配置了模拟对象,以便每当调用getId方法而不是执行它时,始终会返回值1.因此,以下测试将通过:

The line _mock.Setup(x => x.getId(It.IsAny<int>())).Returns(1) configures your mock object so that whenever you call the getId method, instead of executing it, the value 1 will always be returned. So, the following test would pass:

[TestMethod]
public void returngetId_Always1()
{
    // ... Build up our mock object
    _mock.Setup(x => x.getId(It.IsAny<int>())).Returns(1);
    Assert.AreEqual(1, _mock.Object.getId("foo"));
    Assert.AreEqual(1, _mock.Object.getId("bar"));
}

为了获得要在模拟中调用的方法的实际实现,您必须使用以下配置对类(而不是接口)进行模拟:

In order to get the actual implementation of the method to be invoked from within the mock, you have to mock the class, not the interface, with the following configuration:

[TestMethod]
public void returngetId_CallBase()
{
    var mock = new Mock<MyTest>() { CallBase = true };
    // add other method setups here. DO NOT setup the getId() method.
    Assert.AreEqual(2, _mock.Object.getId("foo"));
    Assert.AreEqual(2, _mock.Object.getId("bar"));
}

这将使模拟能够针对未提供模拟设置的任何方法遵循基本实现.

This will allow the mock to defer to the base implementation for any methods for which a mocking setup has not been provided.

这篇关于验证MOQ单元测试方法的返回值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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