7

ある時点で、私のコードはCSVRecordに触れる必要があり、そのモック バージョンを作成する方法がわかりません。

クラスは final であるため、モックすることはできません。コンストラクターはプライベートなので、インスタンスを作成できません。CSVRecordクラスを使用するコードのテストにはどのようにアプローチしますか?

現時点で機能する唯一の解決策は、テスト フィクスチャを解析してオブジェクトのインスタンスを取得することです。これは私の最善のアプローチですか?

4

1 に答える 1

1

パワーモックを使用できます。詳細: https://github.com/powermock/powermock/wiki/mockfinal

例:

import org.apache.commons.csv.CSVRecord;
import static org.junit.Assert.assertEquals;
import org.junit.Test;
import org.junit.runner.RunWith;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
import org.powermock.core.classloader.annotations.PrepareForTest;
import org.powermock.modules.junit4.PowerMockRunner;

@RunWith(PowerMockRunner.class)
@PrepareForTest({CSVRecord.class}) // needed to mock final classes and static methods
public class YourTestClass {
    @Test
    public void testCheckValidNum_null() {
        String columnName = "colName";
        CSVRecord record = mock(CSVRecord.class);
        String contentsOfCol = "hello";
        String result;

        when(record.get(columnName)).thenReturn(contentsOfCol);

        result = record.get(columnName);

        assertEquals(contentsOfCol, result);
    }
}

これが私のMavenインクルードです(ライブラリの新しいバージョンがあり、これは私が使用しているものです):

<dependency>
    <groupId>org.powermock</groupId>
    <artifactId>powermock-module-junit4</artifactId>
    <version>1.7.4</version>
    <scope>test</scope>
</dependency>
<dependency>
    <groupId>org.powermock</groupId>
    <artifactId>powermock-api-mockito</artifactId>
    <version>1.7.4</version>
    <scope>test</scope>
</dependency>
<dependency>
    <groupId>junit</groupId>
    <artifactId>junit</artifactId>
    <version>4.12</version>
    <scope>test</scope>
</dependency>
<dependency>
    <groupId>org.mockito</groupId>
    <artifactId>mockito-all</artifactId>
    <version>1.8.5</version>
    <scope>test</scope>
</dependency>
于 2019-10-06T01:36:59.933 に答える