7

At some point my code needs to touch a CSVRecord and I can't figure out a way to create a mock version of it.

The class is final so it can't be mocked. The constructor is private so I can't create an instance of it. How does one approach testing code that uses the CSVRecord class?

Right now the only solution that works is parsing a test fixture to get an instance of the object. Is this my best approach?

Martinffx
  • 2,426
  • 4
  • 33
  • 60
  • have a look at http://stackoverflow.com/questions/28317147/how-do-i-mock-a-class-marked-final-and-has-a-private-constructor-using-jmockit – Naman Jan 16 '17 at 06:12
  • Can you please provide more detail about mocking framework you are using. A sample snippet will be helpful. – Nisheeth Shah Jan 16 '17 at 06:47
  • I'm using mockito, so no mocking final's as per @nullpointer 's example using jmock – Martinffx Jan 16 '17 at 09:33

1 Answers1

2

You can use Powermock. More info: https://github.com/powermock/powermock/wiki/mockfinal

example:

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);
    }
}

Here are my maven includes (there are newer versions of libraries, this is just what I'm using):

<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>
Creature
  • 994
  • 1
  • 12
  • 27