Search code examples
javamutation-testingpitest

Excluding certain lines of code in PITest


I am using the excellent PITest framework. I was wondering if there is something equivalent to Sonars "// NOSONAR" in PITest, whereby certain lines just get excluded from PITest coverage (so it's not red on the report)? I know methods and classes can be excluded, I am just looking for something more fine grained at line level.

The use case I have is as follows:

public enum FinancialStatementUserType {
CONSUMER, BUSINESS, RETAILER;

}

    public static RecipientType toRecipientType(FinancialStatementUserType userType) {
        Assert.notNull(userType, "userType is null");

        switch (userType) {
           case BUSINESS:
           case CONSUMER:
               return RecipientType.CustomerPerson;
           case RETAILER:
            return RecipientType.Seller;

        default:
            throw new IllegalStateException(String.format("No RecipientType for financial statement user type: %s", userType));
    }
}

The problem I have is that 'default' clause unreachable because all the enums are currently covered by the switch statement. The reason we added the 'detault' statement (besides the fact that it's a good practice), is for the case that the enums get extended in the future.

Any ideas?


Solution

  • The is no way to exclude code on a per line level in pitest - it works on the compiled bytecode so has no access to tags and comments in the code as these are lost at compile time.

    The most fine grained exclusion you can do out of the box is at the method level.

    For the particular case you highlight here a possible option is to change your coding style.

    If RecipientType type and FinancialStatementUserType are strongly related you can ensure logic does not break on the addition of a new FinancialStatementUserType by making the relationship explicit.

    enum FinancialStatementUserType {
      CONSUMER(RecipientType.CustomerPerson), 
      BUSINESS(RecipientType.CustomerPerson), 
      RETAILER(RecipientType.Seller);
    
      private final RecipientType recipientType;  
    
      FinancialStatementUserType(String recipientType) {
        this.recipientType = recipientType;
      }
    
      RecipientType recipientType() {
        return recipientType;
      }
    
    }