Save 37% off PRO during our Black Friday Sale! »

Dependency Injection and Unit Testing in .Net Core

Dependency Injection and Unit Testing in .Net Core

Dependency Injection and Unit Testing in .Net Core

A dive into dependency injection in traditional .Net applications and ASP.Net Core. Followed by how dependency injection enables unit testing in .Net core and EF core. Code examples of how to unit test at the controller, service, and data layers.


Chris Ayers

April 21, 2020


  1. The perfect pair Chris Ayers Dependency Injection & Unit Testing

  2. Chris Ayers DevOps Lead @ New Signature Linkedin: /in/chris-l-ayers/ Twitter:

    @Chris_L_Ayers Projects: /UnitTestingDemo /DependencyInjectionDemo
  3. Topics • Dependency Injection • Why? • SOLID • Design

    Patterns • Types • Features • DEMO • Unit Testing • Terms • Test Layout and Naming • Mocking • Best Practices • DEMO
  4. Why? • Clarity • Maintainability • Reuseability • Modularity •

    Testability • Use Different Implementations
  5. SOLID • Single Responsibility Principle • Open/Closed Principle • Liskov

    Substituion Principle • Interface Segregation Principle • Dependency Inversion Principle
  6. Patterns • Façade • Factory • Strategy • Visitor •

  7. Façade Pattern Client -complexFacade Façade +ComplexProcess Subsystem 1 +ComplexStep1 Subsystem

    2 +ComplexStep2 Subsystem 3 +ComplexStep3 Subsystem 4 +ComplexStep4
  8. Factory Pattern Client -shapeFactory <<Interface>> Shape +draw() ShapeFactory +GetShape() :

    Shape Circle +draw() Square +draw() Triangle +draw() Implements Implements Implements Creates
  9. Strategy Pattern <<Interface>> CookingMethod +Cook() Dinner -cookingMethod: CookingMethod Microwave +Cook()

    ToasterOven +Cook() Oven +Cook() Implements Implements Implements Uses
  10. Types of Dependency Injection

  11. No Dependency Injection • Not using interfaces to reduce coupling

    • Hard to test • No clear understanding of relationships between different classes
  12. Property Injection • Initialization not guaranteed • Can be good

    for bigger/complex objects
  13. Method Parameter Injection • When a dependency is used for

    only method and is an edge case
  14. Constructor Injection • Clear understanding of dependencies

  15. Path to Loosely Coupled Classes Tightly Coupled Classes Implement IoC

    using Factory Pattern Implement DIP by creating Abstractions Implement Dependency Injection Use IoC Container Loosely Coupled Classes
  16. Dependency Injection - Scopes Transient Scoped Singleton

  17. Dependency Injection - Features Composition Root Configuration Scopes Factory Support

  18. Dependency Injection - Frameworks .Net Core Unity Castle Windsor Ninject

    AutoFac SimpleInjector Spring.NET StructureMap
  19. Dependency Injection - DEMO


  21. Decoupling is essential for unit testing. DI is a great

    way to achieve decoupling. Unit Testing
  22. Unit Testing – Terms (SUT) System Under Test or (CUT)

    Class Under Test Test Doubles Fake Mock Stub Spy Dummy Objects
  23. Unit Testing - Architectures • Easy to Test Code •

    Inversion of Control (IoC) • Interface Segregation • Functional Programming • Hard to Test code • It is tightly coupled to the concrete implementation. • It violates the Single Responsibility Principle. • It lies about its dependencies. • It is hard to understand and maintain.
  24. Unit Testing - Layout Split up tests by assembly/project. •

    Ex: if you have two libraries: foo.dll, bar.dll • have 2 unit test assemblies: foo.tests.dll, bar.tests.dll Try to have at least 1 test class per class • Ex: if you have two classes in project foo: a.cs, b.cs • have 2 unit test classes in project foo.tests: aTests.cs, bTests.cs • If there are a lot of methods, or tests for some methods, split it up if there are a too many tests in one class. Use folders to mirror layout and namespaces of target project
  25. Unit Testing - Naming Name test class for the class

    under test • Foo.cs -> FooTests.cs [UnitOfWork_StateUnderTest_ExpectedBehavior] Examples • public void GetLines_twoLineString_returnsTwoStrings() • public void GetNonWhitespaceLines_null_Throws() • public void ReplaceMultiple_stringWithHashNonMatchingMappings_String() • public void ReplaceMultiple_stringMatchingMappings_UpdatedString()
  26. Unit Testing – Frameworks Nunit Xunit MStest

  27. Mocking – Frameworks Moq NSubstitute JustMock FakeItEasy

  28. Unit Testing – Gotchas Usually only works for Interfaces or

    Virtual Methods. Statics can be difficult; refactoring can help or Microsoft Fakes Mocking can make assumptions about boundaries
  29. Unit Testing – Best Practices AAA Arrange Act Assert One

    Assert Per Test Method Avoid Test Interdependence Keep It Short, Sweet, and Visible Recognize Test Setup Pain as a Smell Add Them to the Build
  30. Unit Testing – What is a good test? Fast Isolated

    Repeatable Self- Checking Timely
  31. Unit Testing - DEMO

  32. Questions? I might have answers