最小起订量 - 模拟方法 returns 空
Moq - Mock method returns null
AddAsync 方法总是 returns 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);
}
在您的模拟设置中,您是这样说的:
mockFileService.Setup(f => f.AddAsync(
file, "pathToFolder", "nameFile"))....
这就是说,任何时候 AddAsync
方法在您的 mock 上使用这些确切的参数值调用,并且对于对象引用,它也必须是您刚刚创建的同一个对象。相反,您应该使用 Moq 提供的 It.AsAny
方法,例如:
mockFileService.Setup(f => f.AddAsync(
It.AsAny<IFormFile>(), It.AsAny<string>(), It.AsAny<string>()))....
AddAsync 方法总是 returns 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);
}
在您的模拟设置中,您是这样说的:
mockFileService.Setup(f => f.AddAsync(
file, "pathToFolder", "nameFile"))....
这就是说,任何时候 AddAsync
方法在您的 mock 上使用这些确切的参数值调用,并且对于对象引用,它也必须是您刚刚创建的同一个对象。相反,您应该使用 Moq 提供的 It.AsAny
方法,例如:
mockFileService.Setup(f => f.AddAsync(
It.AsAny<IFormFile>(), It.AsAny<string>(), It.AsAny<string>()))....