I've created a few small fluent interfaces through method chaining. They typically call a number of Repositories that fetch data from webservices / databases.
How should I go about unit testing methods that use the fluent interface?
Public IEnumberable<Computer> FindComputers(string serialNumber)
{
return Computers.FindBySerialNumber("YBCX00900")
.AttachConfiguration()
.EnsureAllComputersHaveConfiguration();
}
I can unit test the individual components of the fluent interface, but if I want to unit test the FindComputers method above what should I do?
I'd like to find an easily maintainable approach.
I think that the FI is doing more than it needs to. I assume you are using Computers as a data mapper and also use it for building a query. From what you have shown the query is built up from this:
rule 1: find configured computer with serial number = "whatever" and has-config = true.
rule 2: find not-config computer with serial number = "whatever and has-config = true.
rule 3: find configured computer with serial number = "whatever" and has-config = false.
rule 4: find not-config computer with serial number = "whatever" and has-config = false.
rule 5: find all computer with serial number = "whatever" and has-config = true.
rule 6: find all computer with serial number = "whatever" and has-config = false.
and so on...
Now some of these rules that can be implemented seem to be incorrect. rule 2 and rule 3 seem to be at cross purposes. rule 5 and rule 6 does what? Is this about right?
Because you've implemented an object that breaks SRP. The first step is to break the query builder from the data mapper. Build your FI query object then pass it into the mapper.
Now you can test FindComputers making sure that FI query object is sent to a data mapper. Because you now can build a FI query object you can test it. And you can test that the data mapper uses a query object.
What if in the future you want to find computers by location. If you keep the same code as you wrote you would have to add a method FindByLocation and before you know it you have a god object. smelly!
Can you mock your Repositories? While some will advocate a more pure approach where you must isolate one method of one class, it would be a decent way to test how FindComputers and the fluent interface work together. And it may be simpler, depending on what the Repository access layer looks like.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With