在web api中单元测试post方法时获取对象null异常

时间:2014-09-29 15:20:21

标签: asp.net-mvc tdd moq asp.net-web-api

MoviesController

/// <summary>
/// Creates a New Movie in Movie Data Source
/// </summary>
/// <param name="movie">Movie</param>
/// <returns>HttpResponseMessage</returns>
public HttpResponseMessage Post(Movie movie)
{
    try
    {
        int i = repository.InsertMovie(movie);
        var response = Request.CreateResponse<Movie>(HttpStatusCode.Created, movie);
        **string uri = Url.Link("DefaultApiWithMovieId", new { movieId = i });**
        response.Headers.Location = new Uri(uri);
        return response;
    }
    catch(Exception ex)
    {
        throw new HttpResponseException(HttpStatusCode.BadRequest);
    }
}

WebApiConfig

config.Routes.MapHttpRoute(
               name: "DefaultApiWithMovieId",
               routeTemplate: "api/{controller}/{movieId}",
               defaults: new { movieId = RouteParameter.Optional }
           );

            config.Routes.MapHttpRoute(
                name: "DefaultApi",
                routeTemplate: "api/{controller}/{id}",
                defaults: new { id = RouteParameter.Optional }
            );

测试方法

[TestMethod]
public void Post_Movie_Returns_StatusCode_Created()
{

    MoviesController controller = new MoviesController(movieRepository.Object);
    var config = new HttpConfiguration();
    var request = new HttpRequestMessage(HttpMethod.Post, "http://localhost/api/movies");
    var route = config.Routes.MapHttpRoute("DefaultApiWithMovieId", "api/{controller}/{movieId}");
    var routeData = new HttpRouteData(route, new HttpRouteValueDictionary { { "controller", "movies" } });
    //var controller = new ProductsController(repo);
    controller.ControllerContext = new HttpControllerContext(config, routeData, request);
    controller.Request = request;
    controller.Request.Properties[HttpPropertyKeys.HttpConfigurationKey] = config;
    Movie movie = new Movie() { Title = "SpiderMan", ReleaseYear = 09, Rating = 4, MovieId = 81, Genre = "Romance", Classification = "Good", Cast = { } };
    movieRepository.Setup(x => x.InsertMovie(It.IsAny<Movie>())).Returns(movie.MovieId);
    var result = controller.Post(movie);
    Assert.AreEqual(HttpStatusCode.Created, result.StatusCode);

}

执行上面的测试用例时,在控制器发布方法中,在突出显示的行中,我正在获得执行 对象引用未设置为对象的实例。

1 个答案:

答案 0 :(得分:0)

您没有将routeData发送到请求中。添加以下行:

controller.Request.Properties[HttpPropertyKeys.HttpRouteDataKey] = routeData;