Take the 2-minute tour ×
Code Review Stack Exchange is a question and answer site for peer programmer code reviews. It's 100% free, no registration required.

I have the following piece of java method code:

@Override
public void applyStates(int timestamp, State[] states) {

    // Calculate the time diff between current time and the time stamp of the given states.
    int diff = getNetworkTime() - timestamp;

    if (diff <= 0) {            
        Log.e("Ignoring states that seem to come from the future!");
        return;
    }

    if (diff >= DIFF_THRESHOLD) {
        Log.w("Ignoring states that are too old. Diff is: " + diff);
        return;
    }

    // Do the real processing here.
}

I'd like this code to be testable (by unit tests), however since it has a flow that's comprised of multiple return statements, it's not so easy for me to do so.

I'd like to verify for example, that depending on the input, i go into the 2 different validation clauses in the beginning of the method.

Is there a better design than this? how can this method be better structured for testabilty?

share|improve this question

closed as off-topic by amon, Jamal, Malachi, Jeff Gohlke, Glenn Rogers Oct 21 '13 at 20:25

  • This question does not appear to be a code review request within the scope defined in the help center.
If this question can be reworded to fit the rules in the help center, please edit the question.

4  
This question appears to be off-topic because the real question is asking “How can I unit-test side effects and/or specific code paths?” and is asking for design help. There is no substantial material for a code review present. This question may be more appropriate for programmers.stackexchange.com. –  amon Oct 21 '13 at 16:24
add comment

1 Answer

up vote 1 down vote accepted

You've got a Policy abstraction that is asking to be teased out. The Policy provides a method that tests "is it valid to do this operation now". In production, the Policy instance checks the time difference to see if it is valid. In test, however, you specify an instance of the policy object that always says no when you want to test that code path.

You've a bit of refactoring to do to make that possible. To make testing easier, you want to inject an instance of policy into the object, so that your test can control which implementation is being used.

@Override
public void applyStates(int timestamp, State[] states) {
    if (! this.policy.isValid(timestamp)) {
        return;
    }

    // ....

So for testing purposes, you might inject a "policy.isValid always returns false" object, and then run your tests and verify that none of the states have been applied (whatever that means).

share|improve this answer
add comment

Not the answer you're looking for? Browse other questions tagged or ask your own question.