{
  "path": "/posts/he-tasks-me-he-heaps-me-i-will-wreak",
  "site": "at://did:plc:yy3apqjlms24kso7ahn7lbmb/site.standard.publication/3mova7c4nho2b",
  "tags": [
    "automated testing"
  ],
  "$type": "site.standard.document",
  "title": "He tasks me; he heaps me.... I will wreak that MOQ upon him.",
  "description": "Use Moq to simplify async testing, with ReturnAsync method. For testing a class that consumes async API, mock it using Task.Delay with Moqs Returns.",
  "publishedAt": "2014-10-03T00:00:00.000Z",
  "textContent": "Enough with the horrific misquotes - this is about Moq and async (that's my slight justification for robbing Herman Melville).\n\n\n\nIt's pretty straightforward to use Moq to do async testing thanks to it's marvellous ReturnsAsync method. That means it's really easy to test a class that consumes an async API. Below is an example of a class that does just that: (it so happens that this class is a Web API controller but that's pretty irrelevant to be honest)\n\nTo mock the _sageService.DeleteAsync method it's as easy as this:\n\nBut wait.... What if there's like... Nothing?\n\nNope, I'm not getting into metaphysics. Something more simple. What if the async API you're consuming returns just a Task? Not a Task of int but a simple old humble Task.\n\nSo to take our example we're going from this:\n\nTo this:\n\nYour initial thought might be \"well that's okay, I'll just lop off the ReturnsAsync statements and I'm home free\". That's what I thought anyway.... And I was \\WRONG\\! A moments thought and you realise that there's still a return type - it's just Task now. What you want to do is something like this:\n\nNo it won't - void is not a real type and much as you might like it to, this is not going to work.\n\nSo right now you're thinking, well Moq probably has my back - it'll have something like ReturnsTask, right? Wrong! It's intentional it turns out - there's a discussion on GitHub about the issue. And in that discussion there's just what we need. We can use Task.Delay or Task.FromResult alongside Moq's good old Returns method and we're home free!\n\nHere's one I made earlier...",
  "canonicalUrl": "https://johnnyreilly.com/posts/he-tasks-me-he-heaps-me-i-will-wreak"
}