Should you unit test order of operations? If so, how?

by Matt Thrower   Last Updated November 09, 2017 18:05 PM

Imagine a psedo-code class like this which does name comparisons:

public class NameComparer
{

    public bool DoNamesMatch(Name name1, Name name2)
    {
        if(WholeNameMatch(name1, name2))
        {
            return true;
        }

        return ProcessorIntensiveFuzzyMatcher(name1.Forename, name2.Forename)
                && ProcessorIntensiveFuzzyMatcher(name1.Surname, name2.Surname)
    }

    private bool WholeNameMatch(Name name1, Name name2)
    {
        if( (name1.Forename == name2.Forename)
            && (name1.Surname == name2.Surname) )
        {
            return true;
        }

        return false
    }

    private bool ProcessorIntensiveFuzzyMatcher(string string1, string string2)
    {
        // complex fuzzy matching
    }
}

Best practice suggests that this class only ought to have one public method, and that we ought to unit test the private methods in this class through that public method.

While I can write various tests that ensure WholeNameMatch and ProcessorIntensiveFuzzyMatcher both do what they're supposed to do, the order of operation is important here. If a developer mistakenly moves one above the other, the program is going to take a massive performance hit.

Is it desirable - and possible - to test this order of operations via the exposed public method?



Answers 1


The premise of your question is incorrect. You don't want to test that first WholeNameMatch is called and then ProcessorIntensiveFuzzyMatcher is called. You want to test

GIVEN WholeNameMatch returns true
WHEN NamesMatch is called
THEN ProcessorIntensiveFuzzyMatch is not called

This is easily done if the fuzzy matching is done by an injected dependency that is mocked by the unit test. Most mocking frameworks allow you to verify that a call did not occur.

If the fuzzy matcher is not an injected dependency, it should be.

kevin cline
kevin cline
November 09, 2017 18:04 PM

Related Questions


What is IBM's CUPRIMDS?

Updated February 18, 2017 10:05 AM

What does stubbing mean in programming?

Updated March 03, 2017 13:05 PM

Integration tests, but how much?

Updated February 28, 2017 08:05 AM

i want a postman's counterpart for mobile developers

Updated December 05, 2017 07:05 AM

How to manage non-unit tests in a project?

Updated April 26, 2017 14:05 PM