Unit test with JUnit4 in Intellij IDEA

Article directory

1, Environmental preparation

1. Install JUnitGenerator

Download the corresponding JUnitGenerator V2.0 - Plugins | JetBrains



Choose File > Setting in Intellij IDEA ]→ [Plugins] → [gear diagram] → [Install Plugin from Disk], and then select the junitgenerator. Jar package you just downloaded.

   choose JUnit 4 for configuration after installation.

                      

2. Add JUnit.jar package to the project

Directly on the official website JUnit download | SourceForge.net Download Junit package, select File > Project Structure > Libraries > plus in the project, and then select the corresponding file.

2, Write test code

1. Write test class in src directory
public class Item{

  private String itemId;
  private String itemPrice;
  private int quantity;

  public Item(String itemId, String itemPrice, int quantity){
    this.itemId = itemId.trim();
    this.itemPrice = itemPrice;
    this.quantity = quantity;
  }

  // ID acquisition of goods
  public String getItemId() {
    System.out.println("itemId : " + itemId);
    return itemId;
  }

  // Quantity acquisition of goods
  public int getQuantity() {
    System.out.println("quantity : " + quantity);
    return quantity;
  }

  // Price acquisition of goods
  public String getItemPrice() {
    System.out.println("itemPrice : " + itemPrice);
    return itemPrice;
  }

}
2. Write a test class in the test directory (if not, create a new test and set it to Test Resources Root)

import org.junit.Assert;
import org.junit.Test;

public class TestJunit {
    private String itemId = "A02";
    private String itemPrice = "$8.88";
    private int quantity = 8;

    private Item item = new Item(itemId, itemPrice, quantity);

    @Test
    public void testGetItemId() {
        Assert.assertEquals(itemId, item.getItemId());
    }

    @Test
    public void testGetQuantity() {
        Assert.assertEquals(quantity, item.getQuantity());
    }

    @Test
    public void testGetItemPrice() {
        Assert.assertEquals(itemPrice, item.getItemPrice());
    }
}
3. Create a new Test run class in the Test directory
import org.junit.runner.JUnitCore;
import org.junit.runner.Result;
import org.junit.runner.notification.Failure;

public class TestRunner {
    public static void main(String[] args) {
        Result result = JUnitCore.runClasses(TestJunit.class);
        for (Failure failure : result.getFailures()) {
            System.out.println(failure.toString());
        }
        System.out.println(result.wasSuccessful());
    }
}

3, Operation results

1. Project directory structure

2. Select test runner to run. If the test is correct, it will return true.

Published 193 original articles, won praise 108, visited 80000+
Private letter follow

Tags: Junit IntelliJ IDEA

Posted on Sun, 12 Jan 2020 01:37:11 -0500 by abhinic