0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

PowerMockとmockitoを同時に使う

Last updated at Posted at 2024-06-26

pom.xml(Mavenを使用している場合)に必要な依存関係を追加

<dependency>
    <groupId>org.mockito</groupId>
    <artifactId>mockito-core</artifactId>
    <version>4.x.x</version>
    <scope>test</scope>
</dependency>
<dependency>
    <groupId>org.powermock</groupId>
    <artifactId>powermock-module-junit4</artifactId>
    <version>2.x.x</version>
    <scope>test</scope>
</dependency>
<dependency>
    <groupId>org.powermock</groupId>
    <artifactId>powermock-api-mockito2</artifactId>
    <version>2.x.x</version>
    <scope>test</scope>
</dependency>

テストクラス

import static org.mockito.Mockito.*;
import static org.powermock.api.mockito.PowerMockito.*;

import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.mockito.junit.MockitoJUnitRunner;
import org.powermock.core.classloader.annotations.PrepareForTest;
import org.powermock.modules.junit4.PowerMockRunner;
import org.powermock.modules.junit4.PowerMockRunnerDelegate;

@RunWith(PowerMockRunner.class)
@PowerMockRunnerDelegate(MockitoJUnitRunner.class)
@PrepareForTest({ClassWithStaticMethod.class})
public class ExampleTest {

    @Mock
    private DependencyClass dependency;

    @Test
    public void testStaticMethod() {
        // 静的メソッドのモック設定
        mockStatic(ClassWithStaticMethod.class);
        when(ClassWithStaticMethod.staticMethod()).thenReturn("mocked value");

        // 通常のモック設定
        when(dependency.someMethod()).thenReturn("some value");

        // テストの実行
        String result = new ClassUnderTest(dependency).methodUnderTest();

        // アサーション
        assertEquals("expected value", result);
    }
}

参考

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?