Wednesday, September 18, 2019

Unit test a Task in C# while using a Func instead of a second method somewhere.

This is probably cleaner than this:

CoOrds coOrds = new CoOrds() { x = 13, y = 42, z = 69 };
IEnumerable<CoOrds> bagOfCoOrds = new CoOrds[] {coOrds};
Func<IEnumerable<CoOrds>> func = () => bagOfCoOrds;
Task<IEnumerable<CoOrds>> task = new Task<IEnumerable<CoOrds>>(func);
Mock<ICoOrdsRepository> coOrdsRepository = new Mock<ICoOrdsRepository>();
coOrdsRepository.Setup(b => b.GetCoOrds(It.IsAny<List<int>>())).Returns(task);

 
 

No wait! Don't do this! In XUnit testing the task never returns. It just hangs up forever. Instead use .FromResult like so:

CoOrds coOrds = new CoOrds() { x = 13, y = 42, z = 69 };
IEnumerable<CoOrds> bagOfCoOrds = new CoOrds[] {coOrds};
Task<IEnumerable<CoOrds>> task = Task.FromResult(bagOfCoOrds);
Mock<ICoOrdsRepository> coOrdsRepository = new Mock<ICoOrdsRepository>();
coOrdsRepository.Setup(b => b.GetCoOrds(It.IsAny<List<int>>())).Returns(task);

No comments:

Post a Comment