January 17, 2017

Writing Web API controller tests

I am fan of TDD principle, and always trying to write tests first. Today I want to show, how I usually test Web API controller. There are two approaches:

1. Unit test
Consider UserController class, which has POST method that registers users.
public class UserController : ApiController
{
    private readonly IRegistrationService registrationService;

    public UserController(IRegistrationService registrationService)
    {
        this.registrationService = registrationService;
    }

    public HttpResponseMessage Post([FromBody]string json)
    {
        var model = new JavaScriptSerializer().Deserialize<RegistrationModel>(json);

        bool success = this.registrationService.Register(model);

        return new HttpResponseMessage(success ? HttpStatusCode.OK : HttpStatusCode.InternalServerError);
    }
}