相关疑难解决方法(0)

返回传递给方法的值

我在接口上有一个方法:

string DoSomething(string whatever);
Run Code Online (Sandbox Code Playgroud)

我想用MOQ模拟这个,以便它返回传入的内容 - 类似于:

_mock.Setup( theObject => theObject.DoSomething( It.IsAny<string>( ) ) )
   .Returns( [the parameter that was passed] ) ;
Run Code Online (Sandbox Code Playgroud)

有任何想法吗?

c# moq mocking

352
推荐指数
3
解决办法
11万
查看次数

Moq使用参数返回Async()

我正在尝试模拟存储库的方法

public async Task<WhitelistItem> GetByTypeValue(WhitelistType type, string value)
Run Code Online (Sandbox Code Playgroud)

使用Moq ReturnsAsync,如下所示:

static List<WhitelistItem> whitelist = new List<WhitelistItem>();

var whitelistRepositoryMock = new Mock<IWhitelistRepository>();

whitelistRepositoryMock.Setup(w => w.GetByTypeValue(It.IsAny<WhitelistType>(), It.IsAny<string>()))
                                    .ReturnsAsync((WhitelistType type, string value) =>
                                    {
                                        return (from  item in whitelist
                                                where item.Type == type && item.Value == value
                                                select item).FirstOrDefault();
                                    });
Run Code Online (Sandbox Code Playgroud)

但我在行中收到此错误"... ReturnsAsync((WhitelistType type ...):

无法将lambda表达式转换为类型'Model.WhitelistItem',因为它不是委托类型

WhitelistType是这样的枚举:

public enum WhitelistType
    {
        UserName,
        PostalCode
    }
Run Code Online (Sandbox Code Playgroud)

我按小时搜索,没有找到任何问题的答案.

有线索吗?

c# unit-testing moq

40
推荐指数
2
解决办法
2万
查看次数

标签 统计

c# ×2

moq ×2

mocking ×1

unit-testing ×1