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

Condividi libro
  1. 300 pagine
  2. English
  3. ePUB (disponibile sull'app)
  4. Disponibile su iOS e 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

Dettagli del libro
Anteprima del libro
Indice dei contenuti
Citazioni

Informazioni sul libro

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.

Domande frequenti

Come faccio ad annullare l'abbonamento?
È semplicissimo: basta accedere alla sezione Account nelle Impostazioni e cliccare su "Annulla abbonamento". Dopo la cancellazione, l'abbonamento rimarrà attivo per il periodo rimanente già pagato. Per maggiori informazioni, clicca qui
È possibile scaricare libri? Se sì, come?
Al momento è possibile scaricare tramite l'app tutti i nostri libri ePub mobile-friendly. Anche la maggior parte dei nostri PDF è scaricabile e stiamo lavorando per rendere disponibile quanto prima il download di tutti gli altri file. Per maggiori informazioni, clicca qui
Che differenza c'è tra i piani?
Entrambi i piani ti danno accesso illimitato alla libreria e a tutte le funzionalità di Perlego. Le uniche differenze sono il prezzo e il periodo di abbonamento: con il piano annuale risparmierai circa il 30% rispetto a 12 rate con quello mensile.
Cos'è Perlego?
Perlego è un servizio di abbonamento a testi accademici, che ti permette di accedere a un'intera libreria online a un prezzo inferiore rispetto a quello che pagheresti per acquistare un singolo libro al mese. Con oltre 1 milione di testi suddivisi in più di 1.000 categorie, troverai sicuramente ciò che fa per te! Per maggiori informazioni, clicca qui.
Perlego supporta la sintesi vocale?
Cerca l'icona Sintesi vocale nel prossimo libro che leggerai per verificare se è possibile riprodurre l'audio. Questo strumento permette di leggere il testo a voce alta, evidenziandolo man mano che la lettura procede. Puoi aumentare o diminuire la velocità della sintesi vocale, oppure sospendere la riproduzione. Per maggiori informazioni, clicca qui.
C# and .NET Core Test Driven Development è disponibile online in formato PDF/ePub?
Sì, puoi accedere a C# and .NET Core Test Driven Development di Ayobami Adewole in formato PDF e/o ePub, così come ad altri libri molto apprezzati nelle sezioni relative a Informatik e Programmierung in C#. Scopri oltre 1 milione di libri disponibili nel nostro catalogo.

Informazioni

Anno
2018
ISBN
9781788299923
Edizione
1
Argomento
Informatik

.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...

Indice dei contenuti