I will explain one of the patterns that I usually use when writing unit tests. Apart from the MOQ library, I use Fluent Assertions(http://www.fluentassertions.com). You can search for that in the Nuget Package Manager and install it in the test project. Out-of-the box, Fluent Assertions provides tons of extension methods that help to easily write assertions on the actual as shown below. In the following example, I will run the test against one sample string of my name.
Now, when I will complete this test, it will be as in the following:
- [TestMethod]
- public void CheckStringValue()
- {
- string actual = "Rahul Sahay";
- actual.Should().StartWith("Ra").And.EndWith("ay");
- }
When I run it, it will produce the following result.
Similarly, to verify that a collection contains a specified number of elements and that all elements match a predicate, you can test as shown in the following code snippet.
- [TestMethod]
- public void CheckCollection()
- {
- IEnumerable collection = new[] { 1, 2, 3,4,5 };
- collection.Should().HaveCount(6, "because I thought I put 5 items in the collection");
- }
Now, when I run the preceding test, it will fail and this will fail due to a valid reason, but look at the error message returned.
Let me show it against one of the infrastructure code where I use it.
- [TestMethod]
- public void MovieNameTest()
- {
- IEnumerable<Movie> movie;
- var mockMovieRepository = MovieRepository(out movie);
-
- mockMovieRepository.Setup(obj => obj.GetMovies()).Returns(movie);
-
- IMovieService movieService = new MovieManager(mockMovieRepository.Object);
-
- IEnumerable<MovieData> data = movieService.GetDirectorNames();
-
- data.Should().HaveCount(4, "because we put these many values only");
-
-
- }
Now it has one dependency on MovieRepository (out movie).
- private static Mock<IMovieRepository> MovieRepository(out IEnumerable<Movie> movie)
- {
- Mock<IMovieRepository> mockMovieRepository = new Mock<IMovieRepository>();
-
-
-
- movie = new Movie[]
- {
- new Movie()
- {
- MovieName = "Avatar",
- DirectorName = "James Cameron",
- ReleaseYear = "2009"
- },
- new Movie()
- {
- MovieName = "Titanic",
- DirectorName = "James Cameron",
- ReleaseYear = "1997"
- }
- };
- return mockMovieRepository;
- }
When we run the preceding test, it will again throw a similar error because count is 2 and we're checking for 4.
Thanks for joining me. I hope you will like it.