简体   繁体   English

Moq - 模拟方法返回 null

[英]Moq - Mock method returns null

AddAsync method always returns null AddAsync 方法始终返回 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);
}
        

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.这就是说,任何时候在您的 mock 上使用这些确切的参数值调用AddAsync方法时,对于 object 引用,它也必须是您刚刚创建的相同的 object。 Instead, you should use the It.AsAny methods provided by Moq, for example:相反,您应该使用 Moq 提供的It.AsAny方法,例如:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM