unit-testing Dependency Injection Property Injection

Help us to keep this website almost Ad Free! It takes only 10 seconds of your time:
> Step 1: Go view our video on YouTube: EF Core Bulk Insert
> Step 2: And Like the video. BONUS: You can also share it!

Example

Property injection allows a classes dependencies to be updated after it has been created. This can be useful if you want to simplify object creation, but still allow the dependencies to be overridden by your tests with test doubles.

Consider a class that needs to write to a log file in an error condition. The class knows how to construct a default Logger, but allows it to be overridden through property injection. However it worths noting that using property injection this way you are tightly coupling this class with an exact implementation of ILogger that is ConcreteLogger in this given example. A possible workaround could be a factory that returns the needed ILogger implementation.

public class RecordProcessor
{
    public RecordProcessor()
    {
        Logger = new ConcreteLogger();
    }

    public ILogger Logger { get; set; }

    public void DoSomeProcessing()
    {
        // ...
        _logger.Log("Complete");
    }
}

In most cases, Constructor Injection is preferable to Property Injection because it provides better guarantees about the state of the object immediately after its construction.



Got any unit-testing Question?