Moq - 模拟方法返回 null
AddAsync 方法始终返回 null
我模拟数据的代码:
var mockFileService = new Mock<IFileService>();
var bytes = Encoding.UTF8.GetBytes("This is a dummy file");
IFormFile file = new FormFile(new MemoryStream(bytes), 0, bytes.Length, "Data", "dummy.pdf");
mockFileService.Setup(f => f.AddAsync(file, "pathToFolder", "nameFile")).ReturnsAsync("pathToFile");
_fileService = mockFileService.Object;
我模拟的接口:
public interface IFileService
{
Task<string> AddAsync(IFormFile file, string pathToFolder, string nameFile);
Task<string> AddAsync(byte[] file, string pathToFolder, string nameFile);
Task AddImagesJpegAsync(Image[] images, string path, string imagesPrefix);
Task<byte[]> GetAsync(string pathToFile);
void DeleteFolder(string path);
void CreateFolder(string path);
}
AddAsync method always returns null
Code where I mocked the data:
var mockFileService = new Mock<IFileService>();
var bytes = Encoding.UTF8.GetBytes("This is a dummy file");
IFormFile file = new FormFile(new MemoryStream(bytes), 0, bytes.Length, "Data", "dummy.pdf");
mockFileService.Setup(f => f.AddAsync(file, "pathToFolder", "nameFile")).ReturnsAsync("pathToFile");
_fileService = mockFileService.Object;
Interface which I mock:
public interface IFileService
{
Task<string> AddAsync(IFormFile file, string pathToFolder, string nameFile);
Task<string> AddAsync(byte[] file, string pathToFolder, string nameFile);
Task AddImagesJpegAsync(Image[] images, string path, string imagesPrefix);
Task<byte[]> GetAsync(string pathToFile);
void DeleteFolder(string path);
void CreateFolder(string path);
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
在您的模拟设置中,您是这样说的:
这意味着任何时候使用这些确切的参数值在您的模拟上调用
AddAsync
方法,并且对于对象引用,它也必须是同一个对象你刚刚创建的。相反,您应该使用 Moq 提供的It.AsAny
方法,例如:In your mock setup, you are saying this:
This is saying that any time the
AddAsync
method is called on your mock with those exact parameter values, and for an object reference, it must also be that same object you just created. Instead, you should use theIt.AsAny
methods provided by Moq, for example: