[JAVA] Check the behavior when the exception specified by expected in JUnit 4 @Test annotation occurs / does not occur

Overview

-Check the behavior when an exception occurs or does not occur in the test in which the exception class is specified in expected of @Test annotation. --Check the behavior with the sample program --Use JUnit 4.12

About expected @Test annotation

The @Test annotation expected makes the test successful when the specified exception is thrown. The test fails if the specified exception is not thrown.

Test (JUnit API)

Optionally specify expected, a Throwable, to cause a test method to succeed if and only if an exception of the specified class is thrown by the method. If the Throwable's message or one of its properties should be verified, the ExpectedException rule can be used instead.

Sample program

Source code list

├── pom.xml
└── src
    ├── main
    │   └── java
    │       └── com
    │           └── example
    │               └── Calculator.java
    └── test
        └── java
            └── com
                └── example
                    └── CalculatorTest.java

Maven build file pom.xml

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0</modelVersion>

  <groupId>com.example</groupId>
  <artifactId>test</artifactId>
  <version>1.0-SNAPSHOT</version>

  <properties>
    <maven.compiler.source>11</maven.compiler.source>
    <maven.compiler.target>11</maven.compiler.target>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
  </properties>

  <dependencies>
    <!-- https://mvnrepository.com/artifact/junit/junit -->
    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>4.12</version>
      <scope>test</scope>
    </dependency>
  </dependencies>

</project>

Calculator.java

Refer to the sample class introduced in Getting started · junit -team/junit4 Wiki · GitHub.

package com.example;

public class Calculator {
  public int evaluate(String expression) {
    int sum = 0;
    for (String summand : expression.split("\\+"))
      sum += Integer.valueOf(summand);
    return sum;
  }
}

CalculatorTest.java

A test class for the Calculator class.

package com.example;

import static org.junit.Assert.assertEquals;

import org.junit.Test;

public class CalculatorTest {

  // "1+2+3"If 6 is returned, the test is successful.
  @Test
  public void testEvaluate() {
    Calculator calculator = new Calculator();
    int sum = calculator.evaluate("1+2+3");
    assertEquals(6, sum);
  }

  //Test successful if NullPointerException occurs
  @Test(expected = NullPointerException.class)
  public void testEvaluateException() {
    Calculator calculator = new Calculator();
    int sum = calculator.evaluate(null);
  }

  //Test successful if NullPointerException occurs
  // (The test fails because it does not occur this time)
  @Test(expected = NullPointerException.class)
  public void testEvaluateFailed() {
    Calculator calculator = new Calculator();
    int sum = calculator.evaluate("1+2+3");
  }
}

Run the test

Run the test with the mvn test command.

$ mvn test
(Omission)
-------------------------------------------------------
 T E S T S
-------------------------------------------------------
Running com.example.CalculatorTest
Tests run: 3, Failures: 1, Errors: 0, Skipped: 0, Time elapsed: 0.116 sec <<< FAILURE!
testEvaluateFailed(com.example.CalculatorTest)  Time elapsed: 0.017 sec  <<< FAILURE!
java.lang.AssertionError: Expected exception: java.lang.NullPointerException
(Omission)

Results :

Failed tests:   testEvaluateFailed(com.example.CalculatorTest): Expected exception: java.lang.NullPointerException

Tests run: 3, Failures: 1, Errors: 0, Skipped: 0

You can see that the test of the testEvaluateFailed method of the CalculatorTest class has failed. I wrote "@Test (expected = NullPointerException.class)", but NullPointerException did not occur.

Reference material

Recommended Posts

Check the behavior when the exception specified by expected in JUnit 4 @Test annotation occurs / does not occur
How to set when "The constructor Empty () is not visible" occurs in junit
"Do not show again" check does not work in the warning dialog when starting applet
The story when the test folder was not created in Rails
Docker does not work when DOCKER_HOST is specified in WSL2
[JUnit] Test the thrown exception
What to do when rails db: seed does not reflect in the database