I'm writing a unit test, where by I pass in a model and the title field in particular is required.
My test is as follows:
[TestMethod]
[ExpectedException(typeof(Exception), "Movie Title is mandatory")]
public void Create()
{
var mc = new MoviesController();
var model = new Movie
{
Cast = new[] { "Scott", "Joe", "mark" },
Classification = "PG",
Genre = null,
MovieId = 0,
Rating = 5,
ReleaseDate = 2004,
Title = null
};
var rep = mc.Create(model);
}
Which calls this class via the controller:
public int Create(Movie movie)
{
int num;
if (MovieRepository.Movies == null)
{
throw new Exception("Movies datasource is not available");
}
lock (MovieRepository._dsMovies)
{
DataRow str = MovieRepository._dsMovies.Tables["Movie"].NewRow();
int num1 = MovieRepository._pk + 1;
MovieRepository._pk = num1;
int num2 = num1;
movie.MovieId = num2;
str["Id"] = num2;
if (string.IsNullOrEmpty(movie.Title))
{
throw new Exception("Movie Title is mandatory");
}
str["Title"] = movie.Title.Trim();
if (!string.IsNullOrEmpty(movie.Genre))
{
str["Genre"] = movie.Genre.Trim();
}
if (!string.IsNullOrEmpty(movie.Classification))
{
str["Classification"] = movie.Classification.ToString();
}
str["Rating"] = movie.Rating;
str["ReleaseDate"] = movie.ReleaseDate;
MovieRepository._dsMovies.Tables["Movie"].Rows.Add(str);
if ((movie.Cast == null ? 0 : (int)((int)movie.Cast.Length > 0)) != 0)
{
this.AddCast(movie);
}
MovieRepository._dsMovies.AcceptChanges();
num = num2;
}
return num;
}
As you can see it checks for the title
if (string.IsNullOrEmpty(movie.Title))
{
throw new Exception("Movie Title is mandatory");
}
Can I assert that exception? because as it stands after it fails I click on the output to check the fail log and I see this :
Test Name: CreateMovie
Test Outcome: Failed
Result Message: Test method Project.Test.UnitTest1.CreateMovie did not throw an exception. An exception was expected by attribute Microsoft.VisualStudio.TestTools.UnitTesting.ExpectedExceptionAttribute defined on the test method.
Result StandardOutput:
System.Exception: Movie Title is mandatory
at Movies.MovieRepository.Create(Movie movie)
at Project.Web.Controllers.MoviesController.Create(Movie movie) in c:\Users\Name\Documents\Visual Studio 2013\Projects\Project.Web\Project.Web\Controllers\MoviesController.cs:line 113
According to the result message it says it didn't throw an exception, when I know it did / should