【问题标题】:Mocking an Apache Commons CSV CSVRecord模拟 Apache Commons CSV CSVRecord
【发布时间】:2017-05-30 22:29:57
【问题描述】:

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

这个类是最终的,所以它不能被嘲笑。构造函数是私有的,所以我不能创建它的实例。如何测试使用CSVRecord 类的代码?

目前唯一可行的解​​决方案是解析测试夹具以获取对象的实例。这是我最好的方法吗?

【问题讨论】:

  • 您能否提供有关您正在使用的模拟框架的更多详细信息。一个示例 sn-p 会很有帮助。
  • 我使用的是 mockito,所以没有使用 jmock 的 @nullpointer 示例模拟决赛

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


【解决方案1】:

您可以使用 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>

【讨论】:

    猜你喜欢
    • 2016-07-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-05-07
    • 2017-06-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多