I'm working on a MSTest project which has a reference to a .NET 6.0 project.
I'd like to use Moq for constructing unit tests.
In my .Net project I have an interface IDataAccees
with a method declaration which has the following signature:
Task<(TypeA, Resource[,])> LoadAsync(Int32 size);
FileDataAccess
class implements this interface. Inside
the class definition there's the LoadAsync
implementation as well.
public async Task<(TypeA, Resource[,])> LoadAsync(Int32 size)
{
...
}
private fields in my UnitTest.cs file:
private Resource[,] _mockedTable = null!;
private Mock<IDataAccess> _mock = null!;
private TypeA _a = null;
I'd like to correct / complete the statement _mock.Setup(...)
seen below inside my Unittest.cs file in order to establish the appropriate Moq-management of my LoadAsync()
method, however I have doubts about this.
_mockedTable = new Resource[100, 100];
_mock = new Mock<IDataAccess>();
_mock.Setup(mock => mock.LoadAsync(It.IsAny<Int32>()))
.Returns(() => Task.FromResult( ));
CodePudding user response:
Assuming that you want to return the _mockedTable
object from your mocked class, you could do this:
_mock.Setup(mock => mock.LoadAsync(It.IsAny<Int32>()))
.ReturnsAsync((new TypeA(), _mockedTable));
CodePudding user response:
Constructing the response
var response = new ValueTuple<TypeA, Resource[,]>(_a, _mockedTable);
//OR simply just
var response = (_a, _mockedTable);
Setting up the mocked object
_mock.Setup(mock => mock.LoadAsync(It.IsAny<Int32>()))
.ReturnsAsync(response);
//OR in case moq with version greater than 4.16
_mock.Setup(mock => mock.LoadAsync(It.IsAny<Int32>()).Result)
.Returns(response);