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.


running the test
Now, when I will complete this test, it will be as in the following:

  1. [TestMethod]
  2. public void CheckStringValue()
  3. {
  4. string actual = "Rahul Sahay";
  5. actual.Should().StartWith("Ra").And.EndWith("ay");
  6. }
When I run it, it will produce the following result.

produce
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.
  1. [TestMethod]
  2. public void CheckCollection()
  3. {
  4. IEnumerable collection = new[] { 1, 2, 3,4,5 };
  5. collection.Should().HaveCount(6, "because I thought I put 5 items in the collection");
  6. }
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.

error message

Let me show it against one of the infrastructure code where I use it.
  1. [TestMethod]
  2. public void MovieNameTest()
  3. {
  4. IEnumerable<Movie> movie;
  5. var mockMovieRepository = MovieRepository(out movie);
  6. mockMovieRepository.Setup(obj => obj.GetMovies()).Returns(movie);
  7. IMovieService movieService = new MovieManager(mockMovieRepository.Object);
  8. IEnumerable<MovieData> data = movieService.GetDirectorNames();
  9. data.Should().HaveCount(4, "because we put these many values only");
  10. }
Now it has one dependency on MovieRepository (out movie).
  1. private static Mock<IMovieRepository> MovieRepository(out IEnumerable<Movie> movie)
  2. {
  3. Mock<IMovieRepository> mockMovieRepository = new Mock<IMovieRepository>();
  4. //Mock return as GetMovies returns that, so we are not going to hit db
  5. //we are going to return mocked up entity
  6. movie = new Movie[]
  7. {
  8. new Movie()
  9. {
  10. MovieName = "Avatar",
  11. DirectorName = "James Cameron",
  12. ReleaseYear = "2009"
  13. },
  14. new Movie()
  15. {
  16. MovieName = "Titanic",
  17. DirectorName = "James Cameron",
  18. ReleaseYear = "1997"
  19. }
  20. };
  21. return mockMovieRepository;
  22. }
When we run the preceding test, it will again throw a similar error because count is 2 and we're checking for 4.

error

Thanks for joining me. I hope you will like it.