How to use Classloader.getResources() correctly in Java?

Asked

Viewed 86 times

0

I am unable to capture the right path from where my CSV file is through this line of code below using Classloader.getResources();

@RunWith(MockitoJUnitRunner.class)
public class IndicioActionTest {

    public File getFile(String nomeArquivo) {
        ClassLoader classLoader = getClass().getClassLoader();
        URL resource = classLoader.getResource("csvs/" + nomeArquivo);
        return new File(resource.getPath());
    }
}

The construction of the algorithm is wrong because the variable Resource is seeing null.

My file is here;

inserir a descrição da imagem aqui

I would like to say that this post is not duplicate, because last week I posted something similar!

I need to implement a unit test of an application resource that is an upload of files CSV, with this I have to capture various file information, the first times I made the post in search to clarify questions, I was guided here by Stackoverflow to uncouple more the method responsible for uploading CSV file, and that’s exactly what I did.

I need to implement a unitary test of this method.

public String uploadArquivo() {

        try {

            removeInSession(LISTA_TIPO_INDICIOS);
            removeInSession(LISTA_INDICIOS);
            removeInSession(LISTA_ERRO);

            final File arquivoLeitura = new File(getArquivo());

            final LineNumberReader linhaLeitura = new LineNumberReader(new FileReader(arquivoLeitura));
            linhaLeitura.skip(arquivoLeitura.length());
            final int qtdLinha = linhaLeitura.getLineNumber() + 1;

            final BufferedReader leitor = new BufferedReader(new InputStreamReader(new FileInputStream(getArquivo())));

            String linha = null;

            leitor.readLine();

            for (int indiceIndicio = 2; indiceIndicio <= qtdLinha; indiceIndicio++) {
                statusMatricula = false;
                linha = leitor.readLine();

                if (linha == null) {
                    break;
                }

                final String[] dadosCSV = linha.split(VIRGULA);
                final int numberPositions = dadosCSV.length;

                setNumberPositions(numberPositions);

                boolean resultValidation = false;

                resultValidation = verificadorFluxoCSV(dadosCSV);

                if (getNumberPositions() <= 6) {
                    if (resultValidation) {
                        erroCSVList = ErroCSV.verificarErros6Linhas(dadosCSV, tipoIndicio, uJ, naturezaIndicio,
                                expressaoInvalida, validadorCPF, erroCSVList, indiceIndicio);
                        addInSession(LISTA_ERRO, erroCSVList);

                    } else {
                        verificarListaIndicios(listaTotalIndicio, listaIndicioEntity, uJ, tipoIndicio, dadosCSV);
                    }
                } else if (getNumberPositions() > 6 && getNumberPositions() < 13) {
                    if (resultValidation) {

                        erroCSVList = ErroCSV.verificarErros12Linhas(dadosCSV, tipoIndicio, uJ, naturezaIndicio,
                                expressaoInvalida, validadorCPF, erroCSVList, indiceIndicio, dataValidaEncontrada,
                                tipoVinculo, usuarioCorporativo);
                        addInSession(LISTA_ERRO, erroCSVList);

                    } else {
                        verificarListaIndicios(listaTotalIndicio, listaIndicioEntity, uJ, tipoIndicio, dadosCSV);
                    }
                } else if (getNumberPositions() >= 13) {

                    if (resultValidation) {

                        erroCSVList = ErroCSV.verificarErros12Linhas(dadosCSV, tipoIndicio, uJ, naturezaIndicio,
                                expressaoInvalida, validadorCPF, erroCSVList, indiceIndicio, dataValidaEncontrada,
                                tipoVinculo, usuarioCorporativo);

                        addInSession(LISTA_ERRO, erroCSVList);

                    } else {
                        verificarListaIndicios(listaTotalIndicio, listaIndicioEntity, uJ, tipoIndicio, dadosCSV);

                    }

                }

            }

            leitor.close();

        } catch (

        final FileNotFoundException e) {
            logger.error(e);
            erroInterno();
            e.printStackTrace();
        } catch (final IOException e) {
            logger.error(e);
            erroInterno();
            e.printStackTrace();
        }

        return PAGE_IMPORTAR;
    }

To implement the unitary file upload tests, it is a good practice instead of using the upload file at runtime, to put the CSV file inside the application itself and then implement the test class. I put in that way;

/src/test/resources/csvs/

The expected result has to be similar to this in the test class;

inserir a descrição da imagem aqui

Attempts made=======================================================

@Test
public void verificadorFluxoCSVTest() throws IOException {
    String caminho = new File("").getAbsolutePath() + "\\resources\\csvs\\teste.csv";

    final LineNumberReader linhaLeitura = new LineNumberReader(new FileReader(caminho));

    linhaLeitura.skip(caminho.length());
    final int qtdLinha = linhaLeitura.getLineNumber() + 1;

}

To be able to partially solve my problem, it just didn’t get completely right because the variable path has to be a File and not a String.

I tried to make the modification, but I succeeded;

  • What are you calling the getFile? Post the code for this part of the test or the entire test. As shown, the problem could simply be the wrong file name passed to getFile.

  • I made a few modifications and tests in my class, and I was successful, as you can see in my post, I did an update, the problem is that I did the path as if it were a String variable, but it has to be a File variable, I tried to make some modifications, but it makes mistakes, there’s very little left to complete, I still need help.

No answers

Browser other questions tagged

You are not signed in. Login or sign up in order to post.