Mocking via virtual method Fake Dependencies with an Interface and Dependency Injection is easy and the usual approach. But how can you fake without Dependency Injection or an Interface. I will show you two situations that came up in production code.
Factory Method The first situation is a small AWS Lambda function with an http call. We want to mock the .Net HttpClient and write a UnitTest for our Request method.
Our code is often time-dependent. We use the date or time to implement logic and make decisions in our code. The behavior of DateTime.Now or DateTime.UtcNow can differ due to the system, timezone and the time change (summer/winter). This means that we have to control this for our tests.
Take this method for instance:
public double ReturnCurrentOffset() { var result = DateTime.Now - DateTime.UtcNow; return result.TotalMinutes; } As you see, this method calculates the current offset with DateTime.
Test Fixtures Imagine your about to sit down to eat your lunch. The dirty breakfast dish is still on the table. You got three options. You can get a new plate, you can clean the old plate, or you can just eat lunch off the dirty plate. Thats it. New plate, clean plate, dirty plate. The same rules apply to tests.
Transient Fresh Fixture Getting a new plate is what Meszaros calls in the book “XUnit Test Patterns” a Transient Fresh Fixture.