Click here to Skip to main content
15,900,500 members
Articles / All Topics

Fluent Assertions

Rate me:
Please Sign up or sign in to vote.
4.60/5 (2 votes)
7 Jun 2015CPOL1 min read 10.4K   2
Fluent assertions

In this post, I will talk about one of the patterns which I usually use while writing unit tests. Apart from MOQ library, I also use Fluent Assertions. You can search for the same in nuget package manager and install it in the test project. Out of the box, fluent assertions give tons of extensions method which help to easily write assertions on the actual like shown below. In the below example, I am just running the test against one sample string of my name.

1st

Now, when I complete this test, it will look like:

C#
[TestMethod]
        public void CheckStringValue()
        {
            string actual = "Rahul Sahay";
            actual.Should().StartWith("Ra").And.EndWith("ay");
        }

When I run the same, it will produce the below result.

2nd

Similarly, to verify that a collection contains a specified number of elements and that all elements match a predicate, you can test like shown below:

C#
[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 above test, it will fail. And this will fail for a valid reason. But, look at the error message returned by the same.

3rd

Let, me show the same against one of the infrastructure code where I am using the same.

C#
[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). Basically, this is my arrange.

C#
private static Mock<IMovieRepository> MovieRepository(out IEnumerable<Movie> movie)
        {
            Mock<IMovieRepository> mockMovieRepository = new Mock<IMovieRepository>();

            //Mock return as GetMovies returns the same, so we are not going to hit db
            //we are going to return mocked up entity
            movie = new Movie[]
            {
                new Movie()
                {
                    MovieName = "Avatar",
                    DirectorName = "James Cameron",
                    ReleaseYear = "2009"
                },
                new Movie()
                {
                    MovieName = "Titanic",
                    DirectorName = "James Cameron",
                    ReleaseYear = "1997"
                }
            };
            return mockMovieRepository;
        }

When I run the above test, it will again throw a similar error because count is 2 and I am checking for 4.

4th

Thanks for joining me. I hope you like it.

Happy coding!

This article was originally posted at http://myview.rahulnivi.net?p=1927

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Architect Publicis Sapient
India India
Hey there, it's Rahul Sahay! I'm thrilled to be a platform specialist at Publicis Sapient, where I get to work on some exciting projects. I've been honing my skills in various aspects of the software development life cycle for more than 15 years, with a primary focus on web stack development. I've been fortunate to have contributed to numerous software development initiatives, ranging from client applications to web services and websites. Additionally, I enjoy crafting application architecture from scratch, and I've spent most of my time writing platform agnostic and cloud agnostic code. As a self-proclaimed code junkie, software development is more than just a job to me; it's a passion! And I consider myself lucky to have worked with an array of cutting-edge technologies, from .NetCore to SpringBoot 3, from Angular to React, and from Azure to AWS and many more cousin technologies...

- šŸ”­ Iā€™m currently working @ below tech stacks
- Microservices,
- Distributed Systems,
- Spring Boot
- Spring Cloud
- System Design,
- Docker,
- Kubernetes,
- Message Queues,
- ELK Stack
- DotNetCore,
- Angular,
- Azure

- šŸ’¬ Ask me anything about my articles [My View](https://myview.rahulnivi.net/)
- šŸ“« How to reach me: [@rahulsahay19](https://twitter.com/rahulsahay19)
- šŸ“« Github: [@rahulsahay19](https://github.com/rahulsahay19)

Comments and Discussions

 
GeneralMy vote of 3 Pin
Micha C9-Jun-15 0:25
professionalMicha C9-Jun-15 0:25 
GeneralRe: My vote of 3 Pin
rahulsahay209-Jun-15 6:23
rahulsahay209-Jun-15 6:23 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.