Moq - 模拟方法返回 null

发布于 2025-01-12 15:51:55 字数 886 浏览 0 评论 0原文

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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

国产ˉ祖宗 2025-01-19 15:51:55

在您的模拟设置中,您是这样说的:

mockFileService.Setup(f => f.AddAsync(
    file, "pathToFolder", "nameFile"))....

这意味着任何时候使用这些确切的参数值在您的模拟上调用 AddAsync 方法,并且对于对象引用,它也必须是同一个对象你刚刚创建的。相反,您应该使用 Moq 提供的 It.AsAny 方法,例如:

mockFileService.Setup(f => f.AddAsync(
    It.AsAny<IFormFile>(), It.AsAny<string>(), It.AsAny<string>()))....

In your mock setup, you are saying this:

mockFileService.Setup(f => f.AddAsync(
    file, "pathToFolder", "nameFile"))....

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 the It.AsAny methods provided by Moq, for example:

mockFileService.Setup(f => f.AddAsync(
    It.AsAny<IFormFile>(), It.AsAny<string>(), It.AsAny<string>()))....
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文