0
MoviesController獲取對象空例外,而單元測試後方法的WebAPI
/// <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);
}
在執行上面的測試用例時,在In Controller post方法中,在突出顯示的行處,我正在使用exeception 未將對象引用設置爲對象的實例。