C# and .NET Core Test Driven Development
eBook - ePub

C# and .NET Core Test Driven Development

Dive into TDD to create flexible, maintainable, and production-ready .NET Core applications

Ayobami Adewole

Share book
  1. 300 pages
  2. English
  3. ePUB (mobile friendly)
  4. Available on iOS & Android
eBook - ePub

C# and .NET Core Test Driven Development

Dive into TDD to create flexible, maintainable, and production-ready .NET Core applications

Ayobami Adewole

Book details
Book preview
Table of contents
Citations

About This Book

Learn how to apply a test-driven development process by building ready C# 7 and.NET Core applications.About This Bookā€¢ Create tests to quickly detect and resolve issues when writing portable codeā€¢ Uncover code integration issues that improve code quality using continuous integrationā€¢ Set up and use data-driven unit testing to verify your codeWho This Book Is ForThis book is for.NET developers who would like to build efficient applications by implementing principles of test-driven development. C# programming and working knowledge of VS is assumed.What You Will Learnā€¢ Write flexible, maintainable, and verifiable code for.NET Coreā€¢ Write testable code using SOLID principles and dependency injectionsā€¢ Recognize the characteristics of a good unit testā€¢ Structure and group your unit testā€¢ Use mock objects to handle dependenciesā€¢ Set up an end-to-end continuous integration processIn DetailThis book guides developers to create robust, production-ready C# 7 and.NET Core applications through the practice of test-driven development process.In C# and.NET Core Test-Driven Development, you will learn the different stages of the TDD life cycle, basics of TDD, best practices, and anti-patterns. It will teach you how to create an ASP.NET Core MVC sample application, write testable code with SOLID principles and set up a dependency injection for your sample application. Next, you will learn the xUnit testing framework and learn how to use its attributes and assertions. You'll see how to create data-driven unit tests and mock dependencies in your code. You will understand the difference between running and debugging your tests on.NET Core on LINUX versus Windows and Visual Studio. As you move forward, you will be able to create a healthy continuous integration process for your sample application using GitHub, TeamCity, Cake, and Microsoft VSTS.By the end of this book, you will have learned how to write clean and robust code through the effective practice of TDD, set up CI build steps to test and build applications as well as how to package application for deployment on NuGet.Style and approachThe book explores the concepts of test driven development in depth so readers can apply these proven techniques to build sophisticated software with C# and.NET.

Frequently asked questions

How do I cancel my subscription?
Simply head over to the account section in settings and click on ā€œCancel Subscriptionā€ - itā€™s as simple as that. After you cancel, your membership will stay active for the remainder of the time youā€™ve paid for. Learn more here.
Can/how do I download books?
At the moment all of our mobile-responsive ePub books are available to download via the app. Most of our PDFs are also available to download and we're working on making the final remaining ones downloadable now. Learn more here.
What is the difference between the pricing plans?
Both plans give you full access to the library and all of Perlegoā€™s features. The only differences are the price and subscription period: With the annual plan youā€™ll save around 30% compared to 12 months on the monthly plan.
What is Perlego?
We are an online textbook subscription service, where you can get access to an entire online library for less than the price of a single book per month. With over 1 million books across 1000+ topics, weā€™ve got you covered! Learn more here.
Do you support text-to-speech?
Look out for the read-aloud symbol on your next book to see if you can listen to it. The read-aloud tool reads text aloud for you, highlighting the text as it is being read. You can pause it, speed it up and slow it down. Learn more here.
Is C# and .NET Core Test Driven Development an online PDF/ePUB?
Yes, you can access C# and .NET Core Test Driven Development by Ayobami Adewole in PDF and/or ePUB format, as well as other popular books in Informatik & Programmierung in C#. We have over one million books available in our catalogue for you to explore.

Information

Year
2018
ISBN
9781788299923

.NET Core Unit Testing

Unit testing has been one of the most discussed concepts in software development in the last few years. Unit testing is not a new concept in software development; it has been around for quite a while, since the early days of the Smalltalk programming language. Based on the increased advocacy for quality and robust software applications, software developers and testers have come to realize the great benefits unit testing can offer in terms of software product quality improvement.
Through unit testing, developers are able to identify errors in code quickly, which increases the development team's confidence in the quality of the software product being shipped. Unit testing is primarily carried out by programmers and tests, and this activity involves the breaking down of the requirements and functionalities of an application into units that can be tested separately.
Unit tests are meant to be small and run frequently, especially when changes are made to the code, to ensure the working functionalities in a code base are not broken. When doing TDD, the unit test must be written before writing the code to be tested. The test usually serves as an aid for designing and writing the code, and is effectively a documentation for the design and specification of the code.
In this chapter, we will explain how to create basic unit tests and prove the results of our unit tests with xUnit assertions. This following topics will be covered in this chapter:
  • The attributes of a good unit test
  • The current unit testing framework ecosystem for .NET Core and C#
  • Unit testing considerations for ASP.NET MVC Core
  • Structuring unit tests with xUnit
  • Proving unit test results with xUnit assertions
  • The test runners available on both .NET Core and Windows

The attributes of a good unit test

A unit test is a piece of code written to test another code. It is sometimes referred to as the lowest-level test because it is used to test code at the lowest level of an application. The unit test calls the method or class under test to validate and assert assumptions about the logic, function, and behavior of the code being tested.
The main purpose of unit testing is to validate a unit of code under test, to ascertain that the piece of code does what it is designed to do and not otherwise. Through unit testing, the correctness of a unit of code can be proven, this can be achieved only if the unit test is written well. While unit testing will prove the correctness and help to discover bugs in code, code quality might not be improved if the code being tested is poorly designed and written.
When you write your unit tests properly, you can to a certain degree, have confidence that your application will behave correctly when shipped. Through the test coverage obtainable from test suites, you can have the metrics of tests written for methods, classes, and other objects in your code base, and you are provided with meaningful information on how frequently they are being run, along with counts of how many times the tests pass or fail.
With the available test metrics, every stakeholder involved in software development can have access to objective information that can be used to improve the software development process. Unit testing, when iteratively done, can add value to the code by improving the reliability and quality of the code. This is possible through testing the code for errorsā€”the test is run repeatedly many times, a concept known as regression testing, to locate errors that might occur as the software application matures and components that were working earlier break.

Readable

This characteristic of unit tests can not be overemphasized. Similar to the code under test, unit tests should be easy to read and understand. The coding standards and principles are also applicable to tests. Anti-patterns, such as magic numbers or constants, should be avoided as they can clutter tests and make them difficult to read. Integer 10 in the following test is a magic number, as it was directly used. This affects the test readability and clearity:
[Fact]
public void Test_CheckPasswordLength_ShouldReturnTrue() {

string password = "civic";

bool isValid=false;
if(password.Length >=10)
isValid=true;

Assert.True(isValid);
}
There is a good test structuring pattern that can be adopted, it's widely known as the triple A or 3A patternā€”Arrange, Act, and Assertā€”which separates the test setup from its verification. You are to ensure that the required data input by the test is arranged, followed by the lines of code to act on the method under test, and assert that the results from the method under test meet the expectation:
 [Fact]
public void Test_CompareTwoStrings_ShouldReturnTrue() {
string input = "civic";

string reversed = new string(input.Reverse().ToArray());

Assert.Equal(reversed, input);
}
While there is no strict naming convention for tests, you should ensure that the name of a test represents a specific business requirement. The test name should have the expected input as well as state the expected output, Test_CheckPasswordLength_ShouldReturnTrue, this is because, besides serving the purpose of testing application-specific functionality, unit tests are also a rich source of documentation of the source code.

Unit independence

A unit test should basically be a unit, it should be designed and written in a form that allows it to run independently. The unit under test, in this case a method, should have been written to depend subtly on other methods. If possible, the data needed by the methods should be taken through the method parameters or should be provided within the unit, it should not have to request or set up data externally for it to function.
The unit test should not depend on or be affected by any other tests. When unit tests are dependent on each other, if one of the tests fails when run, all other dependent tests will also fail. All the needed data by the code under test should be provided by the unit test.
Similar to the Single Responsibility Principle discussed in Chapter 2, Getting Started with .NET Core, a unit should have only one responsibility and only once concern at any time. The unit should have a single task at any point in time to allow it to be testable as a unit. When you have a method that practically does more than a single task, it is simply a wrapper for units and should be decomposed into the basic units for easy testing:
[Fact]
public void Test_DeleteLoan_ShouldReturnNull() {

loanRepository.ArchiveLoan(12);
loanRepository.DeleteLoan(12);
var loan=loanRepository.GetById(12);

Assert.Null(loan);
}
The issue with the test in this snippet is that there is a lot happening at the same time. And if the test fails, there is no specific way to check which of the method calls caused the failure. This test can be broken down into different tests for clarity and easy maintenance.

Repeatable...

Table of contents