3
3

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.

PowerMockRunnerとParameterizedを一緒に使おう

Posted at

PowerMockRunnerを使っているとパラメータの値が異なるだけなのに、コピペしてテストメソッドを増やしてませんか?

@PowerMockRunnerDelegateを使うことでPowerMockRunnerを使いながらParameterizedランナーやTheoriesランナーを使うことができます。

Parameterizedランナーを使用する場合の定義の仕方は
@PowerMockRunnerDelegate(Parameterized.class)です。
たった1行追加するだけでParameterizedランナーが使えるようになるので、テストメソッドのコピペが不要になりますね。

サンプルソースは下記のようになります。

PowerMockAndParameterized.java
import static org.junit.Assert.*;
import static org.hamcrest.CoreMatchers.is;

import java.util.Arrays;
import java.util.Collection;

import org.junit.Test;
import org.junit.runners.Parameterized;
import org.junit.runners.Parameterized.Parameters;
import org.junit.runner.RunWith;
import org.powermock.api.mockito.PowerMockito;
import org.powermock.core.classloader.annotations.PrepareForTest;
import org.powermock.modules.junit4.PowerMockRunner;
import org.powermock.modules.junit4.PowerMockRunnerDelegate;

@RunWith(PowerMockRunner.class)
@PowerMockRunnerDelegate(Parameterized.class)
@PrepareForTest({System.class})
public class PowerMockAndParameterized {

    private final String input;
    private final String expected;

    public PowerMockAndParameterized(String input, String expected) {
        this.input = input;
        this.expected = expected;
    }
    @Parameters
    public static Collection<Object[]> data() {
        return Arrays.asList(new Object[][] {
                {"A", "B"},
                {"B", "B"}
        });
    }

    @Test
    public void Parameterizedを使うよ() {
        // SetUp
        PowerMockito.mockStatic(System.class);
        PowerMockito.when(System.getenv(input)).thenReturn("B");

        // Test
        String actual = System.getenv(input);

        // Verify
        assertThat(actual, is(expected));
        PowerMockito.verifyStatic();
    }
}
3
3
2

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
3
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?