0
1

PowerMockito を Eclipse に設定するための手順

Posted at

手順 1: Eclipse のセットアップ

Eclipse IDE をインストール
Java 17 に対応している Eclipse IDE をインストールします。

Java SDK の設定
Window > Preferences > Java > Installed JREs から、対象のJavaの SDK を Eclipse に追加して選択します。

手順 2: プロジェクトの作成

Java プロジェクトを作成
File > New > Java Project を選択し、新しいプロジェクトを作成します。

JUnit と Mockito の依存関係を追加
PowerMockito は JUnit および Mockito を前提としています。JUnit5 または JUnit4 を使用できますが、互換性の観点から、JUnit4 の方がより多くの機能がサポートされているため推奨されます。

手順 3: Maven もしくは手動でライブラリの追加

  1. Maven を使用する場合:
    pom.xml に以下の依存関係を追加します。
<dependencies>
    <!-- JUnit 4 -->
    <dependency>
        <groupId>junit</groupId>
        <artifactId>junit</artifactId>
        <version>4.13.2</version>
        <scope>test</scope>
    </dependency>

    <!-- Mockito -->
    <dependency>
        <groupId>org.mockito</groupId>
        <artifactId>mockito-core</artifactId>
        <version>3.12.4</version>
        <scope>test</scope>
    </dependency>

    <!-- PowerMock for Mockito -->
    <dependency>
        <groupId>org.powermock</groupId>
        <artifactId>powermock-module-junit4</artifactId>
        <version>2.0.9</version>
        <scope>test</scope>
    </dependency>

    <dependency>
        <groupId>org.powermock</groupId>
        <artifactId>powermock-api-mockito2</artifactId>
        <version>2.0.9</version>
        <scope>test</scope>
    </dependency>
</dependencies>

. Maven を使用しない場合:
必要な JAR ファイルを手動でダウンロードし、プロジェクトに追加します。必要な JAR ファイルは以下の通りです。

JUnit
Mockito Core
PowerMock API for Mockito
PowerMock JUnit モジュール
これらの JAR を libs フォルダに配置し、ビルドパスに追加します。

手順 4: PowerMockito の使用例

import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mockito;
import org.powermock.api.mockito.PowerMockito;
import org.powermock.core.classloader.annotations.PrepareForTest;
import org.powermock.modules.junit4.PowerMockRunner;

@RunWith(PowerMockRunner.class)
@PrepareForTest(StaticClass.class)
public class PowerMockSampleTest {

    @Test
    public void testStaticMethod() {
        // Static メソッドのモック
        PowerMockito.mockStatic(StaticClass.class);

        // モックの動作を定義
        Mockito.when(StaticClass.staticMethod()).thenReturn("Mocked Result");

        // テスト対象メソッドを呼び出し
        String result = StaticClass.staticMethod();

        // 結果を検証
        Mockito.verify(StaticClass.class);
        assertEquals("Mocked Result", result);
    }
}

上記のコードでは、StaticClass の静的メソッドをモックして、その戻り値をカスタマイズしています。

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