基于对象参数的模拟方法返回 [英] Mock method return based on object parameter

查看:52
本文介绍了基于对象参数的模拟方法返回的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下(简化的)代码:

I have the following (simplified) code:

public string methodName(ClassType object)
{
    If(object.value == 1)
        return "Yes";
    else If(object.value == 2)
        return "No";
    else
        return "whatever";
}

然后我在单元测试中调用这个方法,需要根据对象值模拟返回类型:

I am then calling this method in a unit test, and need to mock the return type based on the object value:

_Service.Setup(x => x.methodName(new methodName { value = 1}).Returns("Yes");
_Service.Setup(x => x.methodName(new methodName { value = 2}).Returns("No");

我知道我写的东西是错误的 - 但我怎样才能做到这一点?

I know what I have written is wrong - but how can I achieve this?

推荐答案

我对 Moq 不太熟悉,但是我认为以下应该可以做到.您应该为参数的每个可能值提供一个 Returns:

I´m not that familiar with Moq, however I asume the following should do it. You should provide a single Returns for every possible value for your parameter:

_Service.Setup(x => x.methodName(It.Is<ClassType>(y => y.value == 1))).Returns("Yes");
_Service.Setup(x => x.methodName(It.Is<ClassType>(y => y.value == 2))).Returns("No");

这样,每当您的 methodName-method 使用 object.value == 1 调用时,都会返回 "Yes",而 object.value == 2 解析为返回 "No" 的方法.

This way whenever your methodName-method is called with object.value == 1, "Yes" is returned, while object.value == 2 resolves to the method returning "No".

但是对我来说这没有多大意义,因为您正在以完全相同的行为嘲笑 methodName 的行为.我想这只是为了研究.

However to me this makes not much sense as you´re mocking the behaviour of methodName with the exact same behaviour. I suppose this is just for research.

这篇关于基于对象参数的模拟方法返回的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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