Mock method return based on object parameter

橙三吉。 提交于 2020-12-11 09:00:42

问题


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?


回答1:


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");

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".

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.




回答2:


You're on the right track. With Moq, you need to specify exactly which setup should match each input. You do it like this:

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

The first line there sets up the mock to return "whatever" whenever this method is called with any value. The following two lines override that behavior for specific values.

I'd check out Moq's Quickstart guide for more details, and the Matching Arguments section in particular.



来源:https://stackoverflow.com/questions/52518396/mock-method-return-based-on-object-parameter

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!