2
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 3 years have passed since last update.

【Swif】Unitテスト入門してみた!【コードつき】

Last updated at Posted at 2022-05-05

目的

Unitテストに触れること
Unitテストへの抵抗を少なくすること

目次

テストされる関数
テストする関数

👇 全体コード
ViewController.swift
UnitTest_1Tests.swift

テストされる関数

ViewController.swift
// 足し算, 10 + 20 -> 30
func add(num1: Int, num2: Int) -> Int {
    num1 + num2
}

// 引き算, 10 - 20 -> -10
func sub(num1: Int, num2: Int) -> Int {
    num1 - num2
}

テストする関数

UnitTest_1Tests.swift
func testAdd() throws {
    let result = Calclator().add(num1: 10, num2: 20)
        
    XCTAssertEqual(result, 30)   // 30 = 10 + 20
}
    
func testSub() throws {
    let result = Calclator().sub(num1: 10, num2: 20)
        
    XCTAssertEqual(result, -10)   // -10 = 10 - 20
}

ViewController.swift

ViewController.swift
import UIKit

class ViewController: UIViewController {
    override func viewDidLoad() {
        super.viewDidLoad()
        view.backgroundColor = .yellow   // 背景色
    }
}

// MARK: - UnitTest
struct Calclator {
    func add(num1: Int, num2: Int) -> Int {
        num1 + num2
    }
    
    func sub(num1: Int, num2: Int) -> Int {
        num1 - num2
    }
}

UnitTest_1Tests.swift

Swiftファイル名が「UnitTest_1Tests.swift」となっている理由は、プロジェクト名が「UnitTest_1」であるから。

UnitTest_1Tests.swift
import XCTest
@testable import UnitTest_1

/*
 ■ UnitTest 実行方法
    - プログラム左の実行ボタンをクリック → 楽
    - Product > Test
    - Command + U → 楽
 
 ■ 関数名: test + テストしたい関数名
 */
class UnitTest_1Tests: XCTestCase {

    func testAdd() throws {
        let result = Calclator().add(num1: 10, num2: 20)
        
        XCTAssertEqual(result, 30)   // 30 = 10 + 20
    }
    
    func testSub() throws {
        let result = Calclator().sub(num1: 10, num2: 20)
        
        XCTAssertEqual(result, -10)   // -10 = 10 - 20
    }

}

参考

2
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
2
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?