Home > OS >  Moq - Mock method returns null
Moq - Mock method returns null

Time:03-09

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);
}
        

CodePudding user response:

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>()))....
  • Related