Consider this small but innocuous piece of code
Code Block | ||
---|---|---|
| ||
using System; using NodaTime; namespace why_spypackage com.celestial.files; import java.time.LocalTime; public class DataClerk { public class DataClerkFileLog { public void ProcessDataClearTheLog() { DateTime// nowSimulated = DateTime.Now; method that would do something to files in the log DateTime stopTime = new DateTime(now.Year, now.Month, now.Day, 20, 0, 0, 0); } } private FileLog theFileLog; public if(void now < stopTime ) ProcessData() { LocalTime now Console.WriteLine("Ready to process the data"= LocalTime.now(); LocalTime FileLog fl = new FileLog(stopTime = LocalTime.parse("20:00"); fl.ClearTheLog(); if( now.isBefore(stopTime) ) { } System.out.println("Ready to process }the data"); } class FileLog fl = new FileLog(); { public void fl.ClearTheLog(); { // Simulated method that would do something to files in the log } } } } } |
There are a number of things that should cause the alarm bells to ring
Line 13 22 constrains the testing of this method. We can only test all paths if the now variable holds a time that is less than 2000 hours
Line 1625, the dependant dependent class could cause an issue if it performs IO, Network, and DB calls.
Line 16 25 can be resolved by injecting the FileLog in through the constructor or ProcessData method. You would need to refactor the code and write a test to prove the CUT is not broken
Line 13 22 can be resolved by refactoring the code so that Lines 1019-11 20 are in a method of their own, and calling that method in Line 13 22 if( getTime() < .isBefore( stopTime ))
Activities
Refactoring the code and writing a new test to support the refactored code - read Activity 1 Observations
Refactor the code so that the FileLog is injected into the DataClerk
Decide how you can test it to verify that the code is still working.
Give attention to whether you should be injecting the class or an interface
Use the NSubstitute When… Do… (or a library you are familiar with that has the same capabilities) feature to set up an expectation that can be tested in an Assert.
Line 11 22 is an issue. The timestamp is hard coded. Not a problem you say. We can remove the magic number so it’s declared as a constant field in the class. This doesn’t really help us because we can only test alternative paths after 8pm. We can use a Spy mechanism to solve this. This can be done by refactoring the code so that the current time is returned from a private method in the DataClerk class.
Turn line 10 19 into a private function
Use the private function to get the time
In the test use NSubstitute
Substitute.ForPartsOf<StubClass>();
to override the returned time so it is greater than 2000 hours.
An alternative design for activity 2 would be to use a lambda expression in line 1322
Think about how this might work, and what would the test look like?
...