mercredi 2 mars 2016

How can I test ASP.Net MVC POST Controller with Moq and Nunit

I want to write a unit test for testing that a new item is created, without actually persisting it to the database. I'm not very familiar with Moq, or mocking in general.

Here's the controller code:

// POST: api/MoviesAPI
[ResponseType(typeof(MovieDTO))]
[Route("api/movies/post")]
public IHttpActionResult PostMovies(MovieDTO movie)
{

    // Validation
    if (String.IsNullOrWhiteSpace(movie.Title))
    {
        return Ok("Movie Title is required");
    }

    if (movie.GenreIds == null || movie.GenreIds.Count == 0)
    {
        return Ok("A new Movie requires at least one genre to be selected");
    }

    if (!ModelState.IsValid)
    {
        return BadRequest(ModelState);
    }
    // /Validation

    //// Create Movie type object to add
    var newMovie = new Movies()
    {
        Title = movie.Title,
        Released = movie.Released
    };


    using (var db = new MoviesContext())
    {
        // Link genres from DB to the new Movie
        newMovie.Genres = new List<Genres>();
        foreach (var g in movie.GenreIds)
        {
            var genreToAdd = db.Genres.FirstOrDefault(x => x.GenreId == g);
            newMovie.Genres.Add(genreToAdd);
        }

        // Try to insert the new Movie
        try
        {
            db.Movies.Add(newMovie);
            db.SaveChanges();
        }
        catch (DbEntityValidationException ex)
        {
            return BadRequest(ex.Message);
        }


        return Ok(movie);
    }

And my incomplete test:

[TestMethod]
public void Insert_NewMovie_IsSuccessful()
{
    //var sut = new Mock<MoviesAPIController>();
    var sut = new MoviesAPIController();
    var model = new MovieDTO();

    //sut.PostMovies(model);

    // TODO: Assert
}

Aucun commentaire:

Enregistrer un commentaire