1

I'm using xUnit with Moq to write unit tests for my app. However, I'm having a hard time to mock the session.

The system under test is a controller action, the method under test uses a TempData["UserMessage"] which always is null as Session isn't initialized.

This is a printscreen of how I'm trying to mock the dependency. enter image description here

Error thrown is at line 65 and is following enter image description here

5
  • Controllers should be dumb, you should instead have a service and test those. Commented Oct 10, 2016 at 20:50
  • I do have services where I store my logic. You mean one shouldn't test it at all? My intent was to test if it returned correct usermessage upon error/correct values sent in. Commented Oct 10, 2016 at 20:52
  • You're just testing that the framework does its thing, I usually try to avoid that. Commented Oct 10, 2016 at 20:53
  • I'm trying to digest what you are writing, but I can't see why I shouldn't test that our actions does various service method calls in correct order etc. Do you have any link to what you are suggesting? I'm really interested in how thin/stupid they should be. Commented Oct 10, 2016 at 21:03
  • Sorry for the delay... answered it Commented Oct 11, 2016 at 2:32

1 Answer 1

1

A general rule of thumb is to avoid having "fat controllers". My controllers literally have the model or arguments they need to execute against a corresponding service. Ideally, your controller actions are a single call with a lot of attributes that describe the endpoint, consider the following:

public class MyThinController : Controller
{
    [
        HttpGet,
        Route("api/[controller]/foos/{bar}"),
        Authorize(Policy = nameof(Policies.StackoverflowOp))
    ]
    public Task<IActionResult> GetFoo([FromRoute] Bar bar,
                                      [FromServices] IExampleService service)
        => service.GetAsync(bar);
}

Then, your only concern should be that given a bar the implementation of IExampleService does correctly get a Foo.

But if you're completely not willing to do it the correct way, there is always a way to do it the wrong way. You're actually looking for the ActionContext.HttpContext which is moq-ready.

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks David, this is makes a lot of sense :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.