Chapter 4. Unit testing with xUnit

 

This chapter covers

  • Executing unit tests with the .NET CLI
  • Writing unit tests with xUnit
  • The difference between facts and theories
  • Logging test output

Testing is an essential part of writing great libraries and applications, and the first line of defense for testing is the unit test. In this chapter you’ll learn how to write unit tests in .NET Core, execute the tests, and add and collect logging data.

4.1. Why write unit tests?

Unit tests are written against the smallest units in a software library, such as classes. A class should have responsibility over a single piece of functionality, and that responsibility should be entirely encapsulated by the class. This is the single responsibility principle, and it’s one of the SOLID software design principles.

SOLID software design

The SOLID design principles are part of the core principles of the agile software development methodology. They’re also just good practice. I recommend reading Clean Code: A Handbook of Agile Software Craftsmanship by Robert C. Martin (Prentice Hall, 2008) to learn more.

When developing a software application, it’s common to want to build all the pieces and test the software’s functionality as a whole. The problem with this approach is that it’s too easy to miss corner cases or unanticipated scenarios. Unit testing gets the developer to think about each unit individually and to verify those units independently.

4.2. Business-day calculator example

 

4.3. xUnit—a .NET Core unit-testing framework

 
 
 

4.4. Setting up the xUnit test project

 
 

4.5. Evaluating truth with xUnit facts

 

4.6. Running tests from development environments

 
 
 

4.7. When it’s impossible to prove all cases, use a theory

 
 
 
 

4.8. Shared context between tests

 
 
 

4.9. Getting output from xUnit tests

 
 
 
 

4.10. Traits

 
 
 

Additional resources

 
 
 

Summary

 
 
 
 
sitemap

Unable to load book!

The book could not be loaded.

(try again in a couple of minutes)

manning.com homepage
test yourself with a liveTest