Mocking a file, filewriter and csvwriter within a method for unit test throwing NullPointerException

限于喜欢 提交于 2021-01-28 00:05:30

问题


I'm trying to mock a file creation , FileWriter operation and CsvWriter operation. I'm using EasyMock to mock file creation , PowerMockito to mock FileWriter and CSVWriter operations. Even after mocking the file creation, junit showing NullPointerException..

My code is,

package example.mypackage.rms.utility;

import java.io.FileNotFoundException;
import java.io.FileWriter;
import java.io.IOException;
import au.com.bytecode.opencsv.CSVWriter;

public class CSVBeanUtil {
    public static boolean writeToCsv(List<String[]> beanList, Path absPath) throws IOException {
        CSVWriter writer = new CSVWriter(new FileWriter(absPath.toAbsolutePath().toString()),
                CSVWriter.DEFAULT_SEPARATOR, CSVWriter.NO_QUOTE_CHARACTER);
        writer.writeAll(beanList);
        writer.close();
        return false;
    }

}

My Test Class is,

package example.mypackage.rms.unittest;

import static org.junit.Assert.assertEquals;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileWriter;
import java.util.ArrayList;
import java.util.List;
import example.mypackage.rms.config.AppConfig;
import example.mypackage.rms.entity.GiveUpFile;
import example.mypackage.rms.utility.CSVBeanUtil;
import org.easymock.EasyMock;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.powermock.api.mockito.PowerMockito;
import org.powermock.core.classloader.annotations.PrepareForTest;
import org.powermock.modules.junit4.PowerMockRunner;
import org.powermock.modules.junit4.PowerMockRunnerDelegate;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.context.web.WebAppConfiguration;
import au.com.bytecode.opencsv.CSVWriter;

@WebAppConfiguration
@ContextConfiguration(classes = { AppConfig.class })
@PrepareForTest(CSVBeanUtil.class)
@RunWith(PowerMockRunner.class)
@PowerMockRunnerDelegate(SpringJUnit4ClassRunner.class)
public class UTCSVBeanUtil {
    @Test
    public void writeBeanToCsv() throws Exception {
        List<String[]> beanList = new ArrayList<String[]>();
        String[] st = new String[5];
        st[0] = "hai";
        beanList.add(st);
        final File fileMock = EasyMock.createMock(File.class);
        EasyMock.expect(fileMock.toPath()).andReturn(Paths.get("test.csv"));
        PowerMockito.mock(CSVWriter.class);
        PowerMockito.mock(FileWriter.class);
        PowerMockito.whenNew(FileWriter.class).withArguments(new File("test.csv")).thenReturn(null);
        PowerMockito.whenNew(CSVWriter.class)
                .withArguments(null, CSVWriter.DEFAULT_SEPARATOR, CSVWriter.NO_QUOTE_CHARACTER).thenReturn(null);

        /*
         * File createdFile= folder.newFile("myfile.csv");
         * ParseCsvToBean.writeBeanToCsv(beanList, "myfile.csv"); String s =
         * FileUtils.readFileToString(createdFile); //not working
         * assertEquals("hai", s);
         */

        /*
         * File createdFile= folder.newFile("myfile.csv");
         * FileUtils.writeStringToFile(createdFile, "hai"); String s =
         * FileUtils.readFileToString(createdFile); //working
         * assertEquals("hai", s);
         */
        boolean expected = false;
        boolean actual = CSVBeanUtil.writeToCsv(beanList, fileMock.toPath());
        assertEquals(expected, actual);

    }
}

And the exception is,

java.lang.NullPointerException at example.mypackage.rms.utility.CSVBeanUtil.writeToCsv(CSVBeanUtil.java:51) at example.mypackage.rms.unittest.UTCSVBeanUtil.writeBeanToCsv(UTCSVBeanUtil.java:114) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source) at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source) at java.lang.reflect.Method.invoke(Unknown Source) at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:47) at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12) at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:44) at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:17) at org.junit.internal.runners.statements.RunBefores.evaluate(RunBefores.java:26) at org.springframework.test.context.junit4.statements.RunBeforeTestMethodCallbacks.evaluate(RunBeforeTestMethodCallbacks.java:73) at org.springframework.test.context.junit4.statements.RunAfterTestMethodCallbacks.evaluate(RunAfterTestMethodCallbacks.java:82) at org.junit.rules.ExternalResource$1.evaluate(ExternalResource.java:48) at org.junit.rules.RunRules.evaluate(RunRules.java:20) at org.springframework.test.context.junit4.statements.SpringRepeat.evaluate(SpringRepeat.java:73) at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:271) at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:224) at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:83) at org.junit.runners.ParentRunner$3.run(ParentRunner.java:238) at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:63) at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:236) at org.junit.runners.ParentRunner.access$000(ParentRunner.java:53) at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:229) at org.springframework.test.context.junit4.statements.RunBeforeTestClassCallbacks.evaluate(RunBeforeTestClassCallbacks.java:61) at org.springframework.test.context.junit4.statements.RunAfterTestClassCallbacks.evaluate(RunAfterTestClassCallbacks.java:68) at org.junit.runners.ParentRunner.run(ParentRunner.java:309) at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.run(SpringJUnit4ClassRunner.java:163) at org.powermock.modules.junit4.internal.impl.DelegatingPowerMockRunner$2.call(DelegatingPowerMockRunner.java:143) at org.powermock.modules.junit4.internal.impl.DelegatingPowerMockRunner$2.call(DelegatingPowerMockRunner.java:136) at org.powermock.modules.junit4.internal.impl.DelegatingPowerMockRunner.withContextClassLoader(DelegatingPowerMockRunner.java:127) at org.powermock.modules.junit4.internal.impl.DelegatingPowerMockRunner.run(DelegatingPowerMockRunner.java:136) at org.powermock.modules.junit4.common.internal.impl.JUnit4TestSuiteChunkerImpl.run(JUnit4TestSuiteChunkerImpl.java:106) at org.powermock.modules.junit4.common.internal.impl.AbstractCommonPowerMockRunner.run(AbstractCommonPowerMockRunner.java:53) at org.powermock.modules.junit4.PowerMockRunner.run(PowerMockRunner.java:59) at org.eclipse.jdt.internal.junit4.runner.JUnit4TestReference.run(JUnit4TestReference.java:50) at org.eclipse.jdt.internal.junit.runner.TestExecution.run(TestExecution.java:38) at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:459) at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:675) at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:382) at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:192)

Please help me to solve this... Thank You...


回答1:


You create FileWriter with String:

new FileWriter(absPath.toAbsolutePath().toString())

But in test you expect a File():

 PowerMockito.whenNew(FileWriter.class).withArguments(new File("test.csv")).thenReturn(null);



回答2:


I have solve this problem by replacing FileWriter with StringWriter, only for testing purpose. Like,

CSVWriter writer = new CSVWriter(new StringWriter(),
            CSVWriter.DEFAULT_SEPARATOR, CSVWriter.NO_QUOTE_CHARACTER);
    PowerMockito.mock(CSVWriter.class);
    PowerMockito.mock(FileWriter.class);
    PowerMockito.whenNew(FileWriter.class)
            .withArguments(Paths.get(uri).toAbsolutePath().toString())
            .thenReturn(null);
    PowerMockito
            .whenNew(CSVWriter.class)
            .withArguments(null, CSVWriter.DEFAULT_SEPARATOR,
                    CSVWriter.NO_QUOTE_CHARACTER).thenReturn(writer);

And it's working fine. Thank You...



来源:https://stackoverflow.com/questions/33796729/mocking-a-file-filewriter-and-csvwriter-within-a-method-for-unit-test-throwing

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!