Mockitoの検証のため環境構築をした

検証環境

  • Ubuntu 20.04(WSL2)
  • Java 17
  • SDKMANはインストールされているものとする

次のコマンドでgradleを導入 $ sdk install gradle

$ gradle -v

------------------------------------------------------------
Gradle 8.7
------------------------------------------------------------

Build time:   2024-03-22 15:52:46 UTC
Revision:     650af14d7653aa949fce5e886e685efc9cf97c10

Kotlin:       1.9.22
Groovy:       3.0.17
Ant:          Apache Ant(TM) version 1.10.13 compiled on January 4 2023
JVM:          17.0.5 (Eclipse Adoptium 17.0.5+8)
OS:           Linux 5.10.16.3-microsoft-standard-WSL2 amd64

検証したいディレクトリで$ gradle initを実行

gradle init

Select type of build to generate:
  1: Application
  2: Library
  3: Gradle plugin
  4: Basic (build structure only)
Enter selection (default: Application) [1..4] 1

Select implementation language:
  1: Java
  2: Kotlin
  3: Groovy
  4: Scala
  5: C++
  6: Swift
Enter selection (default: Java) [1..6] 1

Enter target Java version (min: 7, default: 21): 17

Project name (default: study_mockito2): 

Select application structure:
  1: Single application project
  2: Application and library project
Enter selection (default: Single application project) [1..2] 1

Select build script DSL:
  1: Kotlin
  2: Groovy
Enter selection (default: Kotlin) [1..2] 2

Select test framework:
  1: JUnit 4
  2: TestNG
  3: Spock
  4: JUnit Jupiter
Enter selection (default: JUnit Jupiter) [1..4] 4

Generate build using new APIs and behavior (some features may change in the next minor release)? (default: no) [yes, no] no


> Task :init
To learn more about Gradle by exploring our Samples at https://docs.gradle.org/8.7/samples/sample_building_java_applications.html

build.gradleの設定はこの記事の内容にしたがった

Mockito 3 + JUnit 5 で基本的なモック化とテストをするサンプルコード

plugins {
  id 'java'
}

repositories {
  jcenter()
}

dependencies {
  // Junit 5 を導入
  // https://mvnrepository.com/artifact/org.junit.jupiter/junit-jupiter
  testImplementation 'org.junit.jupiter:junit-jupiter:5.7.0'

  // Mockito 3 を導入
  // https://mvnrepository.com/artifact/org.mockito/mockito-core
  testImplementation 'org.mockito:mockito-core:3.6.0'

  // Mockito による JUnit 5 Extension ライブラリを導入
  // https://mvnrepository.com/artifact/org.mockito/mockito-junit-jupiter
  testImplementation 'org.mockito:mockito-junit-jupiter:3.6.0'
}

test {
  // JUnit platform を使う設定
  useJUnitPlatform()

  // テスト時の出力設定
  testLogging {
    // テスト時の標準出力と標準エラー出力を表示する
    showStandardStreams true
    // イベントを出力する (TestLogEvent)
    events 'started', 'skipped', 'passed', 'failed'
    // 例外発生時の出力設定 (TestExceptionFormat)
    exceptionFormat 'full'
  }
}