我有一个包含数十种方法的类 - 我只需要使用其中两个方法并避免依赖注入。
Task<List<ApplicationUser>> GetAllContractors(CancellationToken cancellationToken);
Task<ApplicationUser> FindByNameAsync(string normalizedUserName, CancellationToken cancellationToken);
Run Code Online (Sandbox Code Playgroud)
我当前的尝试:(适用于所有承包商,因为我不需要任何参数即可生效)
users.AddRange(await ManifestJsonLoader.LoadAsync<List<ApplicationUser>>("Mynamespace.sampleUsers.json"));
var userProviderMock = new Mock<IUserProvider>(MockBehavior.Strict);
userProviderMock.Setup(service => service.GetAllContractors(CancellationToken.None)).Returns(Task.FromResult(users));
userProviderMock.Setup(service => service.FindByNameAsync(It.Is<string>(name => users.FirstOrDefault(d => d.UserName == name) != null), It.IsAny<CancellationToken>()));
Run Code Online (Sandbox Code Playgroud)
我一直在寻找“带有参数的最小起订量方法”,但到目前为止没有一个结果回答了我的问题。也许我在这里寻找错误的关键词。
Func您可以使用重载 for来访问模拟方法委托中的调用参数,以提供接受与您正在模拟的方法完全相同的参数的Returns()lambda 。Moq 会将任何提供的参数传递给您的代表。
文档中的示例:
// access invocation arguments when returning a value
mock.Setup(x => x.DoSomethingStringy(It.IsAny<string>()))
.Returns((string s) => s.ToLower());
Run Code Online (Sandbox Code Playgroud)
注意 1如果您正在模拟具有任何默认参数的方法,则必须显式提供这些参数。
注 2值得一提的是,
Callback如果您需要修改未返回的对象,或者需要根据调用次数更改 Mock 行为,则该选项非常有用。 https://github.com/Moq/moq4/wiki/Quickstart#callbacks
维基页面上有很好的例子:https ://github.com/Moq/moq4/wiki/Quickstart