0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

Javaで簡単なATMアプリを作ってJunit5でテストする

0
Posted at

環境

ProductName: macOS
ProductVersion: 11.2.3
os: Bigsur
IDE: IntelliJ

目的

  • Junit5の学習
  • テストコードの書き方を学ぶ

方法

作成した銀行アプリの機能をJunit5を使ってテストをする

ファイルの構造

.
├── JUNIT_PROJECT.iml
└── bin
    └── co
       └── atm
           ├── Atm.class
           └── AtmTest.class

atmアプリ

Atm.java
package co.atm;

import java.util.Scanner;

public class Atm {
  public static void main(String[] args) {

    //Create an object of the class
    Atm atm = new Atm();
    //クラスのオブジェクトでメソッドをよぶ
    //10,000預ける
    atm.deposit(10000);
    //5,000引き出す
    atm.withdraw(5000);
    //残高を表示
    atm.display();
  }

  Scanner in = new Scanner(System.in);
  float balance; //口座の残高

  public Atm() {
    balance = 0;
    System.out.println("銀行口座のインスタンスを作成 ");
  }

  //預金
  void deposit(float amount) {
    balance += amount;
    System.out.println("預けた金額: " + amount);
  }

  //引き出し
  void withdraw(float amount) {
    balance -= amount;
    System.out.println("引き出した額: " + amount);
  }

  //表示
  void display() {
    System.out.println("引き出し可能な残高: " + balance);
  }

}

テスト内容

  • despositメソッドをつかった場合正しく値が加算されていること
  • Withdrawメソッドを使った場合の正しく値が減算されていること

テストコード

AtmTest.java
package co.atm;

import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.assertEquals;

public class AtmTest {
  @Test
  //1000円を入金し、その後5000円を入金することを確認する。
  public void testDeposit() {
    //準備
    Atm atm = new Atm();
    atm.deposit(1000);
    atm.deposit(5000);

    //期待値
    Float expectedResult = 6000f;

    //assertEqualsで実際の値を取得
    assertEquals(expectedResult, (Float) atm.balance);
  }

  @Test
  //1000円を入金し、その後1000円を引き出すことを確認する。
  public void testWithdraw() {
    //準備
    Atm atm = new Atm();
    atm.deposit(1000);
    atm.withdraw(1000);

    //期待値
    Float expectedResult = 0f;

    //assertEqualsで実際の値を取得
    assertEquals((Float) expectedResult, (Float) atm.balance);
  }
}

テスト結果

image.png

0
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?