Skip to content

Forbid usage of Truth's StandardSubjectBuilder#fail method. #11315

@nrmancuso

Description

@nrmancuso

Noticed at #11270 (comment)

Now that we have come to an agreement on assertThrows, we should enforce usage by adding a MatchXPath module to checkstyle_checks.xml:


➜   cat TestClass.java
import org.junit.Test;

import static com.google.common.truth.Truth.assertWithMessage;
import static org.junit.Assert.assertThrows;

public class TestClass {
    @Test
    public void testMethodBad() {
        try {
            int[] arr = new int[]{};
            int x = arr[2];
            assertWithMessage("IndexOutOfBoundsException expected").fail();
        } catch (IndexOutOfBoundsException ex) {
            assertWithMessage("Invalid error message")
                    .that(ex.getMessage())
                    .isEqualTo("Index 2 out of bounds for length 0");
        }
    }

    @Test
    public void testMethodGood() {

        int[] arr = new int[]{};
        final IndexOutOfBoundsException exception =
                assertThrows(IndexOutOfBoundsException.class,
                        () -> {
                            int i = arr[2];
                        });

        assertWithMessage("Invalid error message")
                .that(exception.getMessage())
                .isEqualTo("Index 2 out of bounds for length 0");

    }
}

➜  cat  config.xml        
<?xml version="1.0"?>
<!DOCTYPE module PUBLIC
        "-//Puppy Crawl//DTD Check Configuration 1.3//EN"
        "http://checkstyle.sourceforge.net/dtds/configuration_1_3.dtd">
<module name="Checker">
    <module name="TreeWalker">
        <module name="MatchXpath">
            <property name="query" value="//METHOD_CALL[./IDENT[@text='assertWithMessage']
          and (./following-sibling::IDENT[@text='fail'])]"/>
            <message key="matchxpath.match"
                     value="'Exceptions should be validated by JUnit's `Assert#assertThrows`."/>
        </module>
    </module>
</module>

➜  java -jar checkstyle-9.3-all.jar -c config.xml TestClass.java 
Starting audit...
[ERROR] TestClass.java:12:30: Exceptions should be validated by JUnit's `Assert#assertThrows`. [MatchXpath]
Audit done.
Checkstyle ends with 1 errors.


We will need to fix existing usages:

➜  checkstyle git:(master) grep -R "assertWithMessage.*fail()" | wc -l
244

Metadata

Metadata

Assignees

No one assigned

    Type

    No type
    No fields configured for issues without a type.

    Projects

    No projects

    Milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions