100% unit test code coverage - how to achieve with "defensive" coding?

How could you get 100% code coverage with the code below?

- (void)methodA {
    mState = Active;
    // do something ...
    methodB();
}

- (void)methodB {
    if (mState != Active) return;
    // do something else ...
}

      

I can easily check parts do something

and do something else

, the problem lies in the line if (mState != Active) return;

methodB

. Since it methodA

always sets the state to Active

, early return will never be done.

I have an early return code in place only if methodB

called elsewhere in the future. The code doesn't make sense to execute if mState

not Active

, so it protects the encoding more or less.

I can add comments to the method that says "this method assumes that the state is active" or whatever, but that does not cause the contract to be active. Throwing exceptions and / or assertion might be here too, but again I'm not sure how I can test this to get 100% code coverage.

I fully understand that for cases like this it probably doesn't make sense to get 100% code coverage, but unfortunately the solution to get is not mine (for now at least). The "bosses" want to do this, and they are unwise about it if you ask me!

+3


source to share


1 answer


First things first: don't get hung up on 100% reach. You can spend a lot of time getting to that number without adding more "quality" to your product!

The implication: If this 100% goal comes from an external driver, it might be worth stepping back and discussing whether the strict 100% goal really works (I think it isn't, but it's more of an opinion).

Assuming you want 100% coverage, I only see one option: you activate your test for A) set mState

to something else than Active

and B) to be able to call methodB()

without going through the method methodA()

.



For example, if a setter is set for this field; and make methodB()

it at least a protected package so that unit test can call the method. But then you make "test-only" changes to your production code - only to hit that magic 100% number.

If mState

not a field but will be returned by a getter, it might be possible to use Mockito spy and partial mock here.

+1


source







All Articles