David Antelo
David Antelo

Reputation: 533

How much should I isolate my method for unit testing?

I have the following method:

public < V extends U > boolean matchesObject (V object, String filter) {

    if (filterIsAny(filter)) return true;

    else {

        List<T> targets = getFilterTarget(object);

        for (T t : targets) if (matches(t, filter)) return true;
        return false;

    }

}

where filterIsAny(filter) is a trivial method (just checks filter != null).

My question is: when I'm unit testing, is it worth to mock this method so that I'm sure that my function follows the correct path in the function, or do I just assume that my filterIsAny(filter) works and test using the real method? In this particular case, it is pretty easy to mock this method, but I have other instances where it would take several lines of code to mock intermediate results returned by trivial functions, such as list.indexOf(object) in a list of mocked objects.

I know it wouldn't be "pure" unit testing, since theoretically I'd be testing more than one function at a time, but how is is worth doing pure unit testing when it takes more work than finding the error in the code in the case of the test failing?

Upvotes: 1

Views: 215

Answers (1)

Austin Schaefer
Austin Schaefer

Reputation: 696

Assume that filterIsAny works until it gains non-trivial logic.

If your function is a wrapper for a single pure Java statement which has no logical branches, you can safely skip writing a unit test for it, and therefore only it in other unit tests. What you do want to test are the various branches in the method to be tested, assuming it has non-trivial logic.

Here, you would setup your filter object such that it produces a true and a false result when testing matchesObject(V object, String filter) based on the logical branch you're testing (no match in collection, one match in collection, invalid collection type (if possible), null input, etc.)

In your case, you can skip the filterIsAny(filter) evaluating to true branch, since you execute a trivial statement return true afterwards.

By the way, consider refactoring to Stream.anyMatch() if possible; it will reduce the number of return statements in your function and enhance readability.

Upvotes: 1

Related Questions