模拟Apache Commons CSV CSVRecord

时间:2017-01-16 06:09:43

标签: java unit-testing mocking mockito apache-commons-csv

在某些时候,我的代码需要触及CSVRecord,我无法找到一种方法来创建它的模拟版本。

课程是最终的,所以不能嘲笑。构造函数是私有的,因此我无法创建它的实例。如何测试使用CSVRecord类的代码?

现在唯一有效的解决方案是解析测试夹具以获取对象的实例。这是我最好的方法吗?

1 个答案:

答案 0 :(得分:0)

您可以使用Powermock。更多信息: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>