Practical Test-Driven Development using C# 7
eBook - ePub

Practical Test-Driven Development using C# 7

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

Practical Test-Driven Development using C# 7

About this book

Develop applications for the real world with a thorough software testing approachAbout This Book• Develop a thorough understanding of TDD and how it can help you develop simpler applications with no defects using C# and JavaScript• Adapt to the mindset of writing tests before code by incorporating business goals, code manageability, and other factors• Make all your software units and modules pass tests by analyzing failed tests and refactoring code as and when requiredWho This Book Is ForThis book is for software developers with a basic knowledge of Test Driven Development (TDD) who want a thorough understanding of how TDD can benefit them and the applications they produce. The examples in this book are in C#, and you will need a basic understanding of C# to work through these examples.What You Will Learn• The core concepts of TDD• Testing in action with a real-world case study in C# and JavaScript using React• Writing proper Unit Tests and testable code for your application• Using different types of test double such as stubs, spies, and mocks • Growing an application guided by tests• Exploring new developments on a green-field application• Mitigating the problems associated with writing tests for legacy applications • Modifying a legacy application to make it testableIn DetailTest-Driven Development (TDD) is a methodology that helps you to write as little as code as possible to satisfy software requirements, and ensures that what you've written does what it's supposed to do. If you're looking for a practical resource on Test-Driven Development this is the book for you. You've found a practical end-to-end guide that will help you implement Test-Driven Techniques for your software development projects.You will learn from industry standard patterns and practices, and shift from a conventional approach to a modern and efficient software testing approach in C# and JavaScript. This book starts with the basics of TDD and the components of a simple unit test. Then we look at setting up the testing framework so that you can easily run your tests in your development environment. You will then see the importance of defining and testing boundaries, abstracting away third-party code (including the.NET Framework), and working with different types of test double such as spies, mocks, and fakes.Moving on, you will learn how to think like a TDD developer when it comes to application development. Next, you'll focus on writing tests for new/changing requirements and covering newly discovered bugs, along with how to test JavaScript applications and perform integration testing. You'll also learn how to identify code that is inherently un-testable, and identify some of the major problems with legacy applications that weren't written with testability in mind. By the end of the book, you'll have all the TDD skills you'll need and you'll be able to re-enter the world as a TDD expert!Style and approachA practical step-by-step approach with real-world case studies.

Frequently asked questions

Yes, you can cancel anytime from the Subscription tab in your account settings on the Perlego website. Your subscription will stay active until the end of your current billing period. Learn how to cancel your subscription.
No, books cannot be downloaded as external files, such as PDFs, for use outside of Perlego. However, you can download books within the Perlego app for offline reading on mobile or tablet. Learn more here.
Perlego offers two plans: Essential and Complete
  • Essential is ideal for learners and professionals who enjoy exploring a wide range of subjects. Access the Essential Library with 800,000+ trusted titles and best-sellers across business, personal growth, and the humanities. Includes unlimited reading time and Standard Read Aloud voice.
  • Complete: Perfect for advanced learners and researchers needing full, unrestricted access. Unlock 1.4M+ books across hundreds of subjects, including academic and specialized titles. The Complete Plan also includes advanced features like Premium Read Aloud and Research Assistant.
Both plans are available with monthly, semester, or annual billing cycles.
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.
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.
Yes! You can use the Perlego app on both iOS or Android devices to read anytime, anywhere — even offline. Perfect for commutes or when you’re on the go.
Please note we cannot support devices running on iOS 13 and Android 7 or earlier. Learn more about using the app.
Yes, you can access Practical Test-Driven Development using C# 7 by John Callaway, Clayton Hunt in PDF and/or ePUB format, as well as other popular books in Computer Science & Programming. We have over one million books available in our catalogue for you to explore.

Information

Abstract Away Problems

These days, it is quite easy to find resources on the internet to integrate into your application. Many provide functionality that would be perfectly suited to any number of applications. After all, why spend time reinventing the wheel when someone else has already done the bulk of the work for you?
In this chapter, we will gain an understanding of:
  • Abstracting a Gravatar service
  • Extending the repository pattern
  • Using a generic repository and Entity Framework

Abstracting away problems

There is an abundance of utilities and libraries these days to help make a full-featured application. It can be quite easy to integrate these third-party systems within your application. At times, however, you may need to replace one third-party library with another. Alternatively, you may find yourself relying on the implementation that a third-party system provides, only to find that the implementation has changed with a later update. How can you avoid these potential problems?
Creating a dependency on code that is outside your control can create problems for you in the future. If a change is introduced in a library that you depend on, it could potentially break your system. Or, if your requirements change and the system no longer fits your specific needs you may have to rewrite large portions of your application.
Don't depend directly on any third-party system. Abstract away the details so that your application depends only on an interface that you define. If you define the interface and expose only the functionality that you need, it can become trivial to make changes when they are required. Changes could include minor updates or replacing whole libraries. You want these changes to have minimal impact on the rest of your application.
Don't rely on third-party implementations; focus on test driving your code.
While developing an application with Test-Driven Development in mind, it can often be tempting to test third-party software. While it is important to ensure that any third-party library or utility works well when integrated into your system, it is best to focus on the behavior of your system. Ensure that your system behaves well with the functionality that you wish to expose.
This means that you should handle the happy path as well as any possible exceptions that may be thrown. Gracefully recovering from an error that crops up will allow your application to continue to function in the event that a third-party service is not functioning as you expect.

Gravatar

The Speaker Meet application uses Gravatar to display speaker, community, and conference avatar images. Gravatar is an online service that associates an email address with an image. Users can create an account and add an image that they wish to be shown by any service that requests their image. The image is retrieved from the Gravatar service by creating an MD5 hash of the user's email address and requesting an image from Gravatar by supplying the hashed value. By relying on the hashed value, the user's email address is not exposed.
The Gravatar service allows the consumer to supply optional parameters to the HTTP call in order to request a specific size, rating, or default image if none is found. Some of these options include:
  • s: The requested size of the image; by default, this is 80 x 80 pixel
  • d: The default image if none is found; options include 404, mm (mystery-man) , identicon, and so on
  • f: Force default; always return the default icon, even if an image is found
  • r: Rating; users can label their image as G, PG, R, and X
By supplying these values, you have some control over the size and types of image you wish to display within your application. The Speaker Meet application relies on the default offerings from Gravatar.

Starting with an interface

Looking at the Gravatar site, it appears that there a number of options available. In order to shield the rest of the application, the functionality of Gravatar will be exposed through a class contained within the Speaker Meet application. This functionality will first be defined by an interface.
The desired interface might look something like this:
 public interface IGravatarService
{
string GetGravatar(string emailAddress);
string GetGravatar(string emailAddress, int size);
string GetGravatar(string emailAddress, int size, string rating);
string GetGravatar(string emailAddress, int size, string rating,
string imageType);
}
To get started, you must first write some tests. Remember, you should not write a line of production code without a failing unit test.

Implementing a test version of the interface

In order to create an interface named IGravatarService, there first must be a need within the application. Create a test within a SpeakerServiceTests Get class entitled ItTakesGravatarService:
[Fact]
public void ItTakesGravatarService()
{
// Arrange
var fakeGravatarService = new FakeGravatarService();
var service = new SpeakerService(_fakeRepository, fakeGravatarService);
}
This will cause a compilation error. Create an IGravatarService and modify the constructor of the SpeakerService so that this is a parameter.
Interface:
public interface IGravatarService
{
}
SpeakerService method:

public SpeakerService(IRepository repository, IGravatarService gravatarService)
{
_repository = repository;
}
In order to get the tests to compile, create a FakeGravatarService that can be supplied to the SpeakerService under test. Remember, you're not testing the FakeGravatarService, merely that the SpeakerService accepts an IGravatarService instance.
Now, ensure that the FakeGravatarServiceGetGravatar method is called when an individual Speaker is requested.
[Fact]
public void ItCallsGravatarService()
{
// Arrange
var expectedSpeaker = SpeakerFactory.Create(_fakeRepository);
var service = new SpeakerService(_fakeRepository, _fakeGravatarService);

// Act
service.Get(expectedSpeaker.Id);

// Assert
Assert.True(_fakeGravatarService.GetGravatarCalled);
}
Modify the interface to add a GetGravatar method:
public interface IGravatarService
{
void GetGravatar();
}
And implement this method in the FakeGravatarService. This is similar to the GetCalled check of the FakeRepository from Chapter 7, Test Driving C# Applications:
public class FakeGravatarService : IGravatarService
{
public bool GetGravatarCalled { get; set; }

public void GetGravatar()
{
GetGravatarCalled = true;
}
}
Next, ensure that the GetGravatar function is executed whe...

Table of contents

  1. Title Page
  2. Copyright and Credits
  3. Packt Upsell
  4. Foreword
  5. Contributors
  6. Preface
  7. Why TDD is Important
  8. Setting Up the .NET Test Environment
  9. Setting Up a JavaScript Environment
  10. What to Know Before Getting Started
  11. Tabula Rasa – Approaching an Application with TDD in Mind
  12. Approaching the Problem
  13. Test-Driving C# Applications
  14. Abstract Away Problems
  15. Testing JavaScript Applications
  16. Exploring Integrations
  17. Changes in Requirements
  18. The Legacy Problem
  19. Unraveling a Mess
  20. A Better Foot Forward
  21. Other Books You May Enjoy