Ilan Greenberg
Ilan Greenberg

Reputation: 101

Is there any way to get 100% of branch coverage?

My task is to cover the whole solution with tests and reach 100% branch and sequence coverage.

I have this method with if statement:

public string ConvertToOrder(string cartCode)
{  
    var cart = CartService.GetCartByCode(cartCode);
    if (cart == null || cart.ItemCount == 0)
    {
        throw new Exception("CartCode does not exist");
    }
}

I have been able to check only 3 scenarios out of 4.
1.when cart is not null and itemCount == 0
2.when cart is not null and itemCount != 0
3.when cart is null and itemCount == 0
4.Forth scenario is not reasonable as i am not able to add item to a null object in my test.

Is there any tool that supports that kind of cases and will show 100% coverage on that? or any kind of way to cover the 4th scenario?

Upvotes: 0

Views: 3129

Answers (2)

David
David

Reputation: 36

Disclaimer: I work at Typemock - the unit testing company The solution coverage tool doesn't know when to ignore these impossible to reach scenarios. You will have to ignore these cases for now. In order to make it easier to locate these hard cases, we advise using the HTML export in which you can see the number of times the if statement was executed and calculate the coverage manually, just to make sure you didn't miss any possible scenario

Upvotes: 1

James Wilson
James Wilson

Reputation: 1636

There isn't a fourth scenario here. The following three scenarios will give complete coverage for your code:

  1. cart is not null and itemCount == 0
  2. cart is not null and itemCount != 0
  3. cart is null

C# (like many programming languages) will evaluate the first operand cart == null and if that is true not evaluate the second operand. Simply this is because once the first operand is true we know the answer is true. See the documentation from Microsoft which covers this behavior of the || operator.

Your question implies that a tool is telling you that you don't have 100% coverage with the first three scenarios. If so, it would be worth looking into why that tool doesn't believe you have 100% coverage.

Upvotes: 1

Related Questions