0

I have this Guard:

protected function validateRemove($key)
{
    if (!isset($this->collection[$key])) {
        throw new CategoryCollectionBadItemException();
    }
}

And the test:

/**
 * @test
 * @expectedException InfluenceDecision\Domain\Exception\Category\CategoryCollectionBadItemException
 */
public function removeMethodMustThrowExceptionWithInvalidKey()
{
    $this->categoryCollection->add(
        new Category(
            null,
            'test category'
        )
    );

    $this->categoryCollection->remove(1);
}

CategoryCollection remove method calls validateRemove method

The test works fine, but the coverage isn't 100% because the test can't access to the last line of validateRemove method:

enter image description here

What's the propper solution?

Torvic
  • 83
  • 1
  • 3
  • 1
    The coverage report is telling you that the closing brace of the method is uncovered? Maybe you need a test that provides a valid collection key. I personally don't think it's worth investing your time in this though, you've already covered the logic you want to cover, and 100% code coverage is mostly just a nice badge to have – scrowler Oct 17 '18 at 13:02

1 Answers1

1

That's happening because you are not testing both the branches of the function, in your test case the function breaks when you throw the exception so it's not technically finishing. You have tested half of the function, even if it's the only logic in there.

If you want the 100% coverage, you need to create a test where $this->collection[$key] is set . In that case, I would suggest to change your function to something like

protected function validateRemove($key)
{
    if (!isset($this->collection[$key])) {
        throw new CategoryCollectionBadItemException();
    }

    return true;
}

and then create another test that asserts true when you call validateRemove() and $this->collection[$key] is set.

Mine is an example as I don't really know how do you use that piece of code!