Junit parameterized tests using file input

后端 未结 3 1668
渐次进展
渐次进展 2021-01-06 05:10

I have a query about using parameterized tests for my unit testing of my APIs. Now instead of building an arraylist like

Arrays.asList(new Object[]{
   {1},         


        
相关标签:
3条回答
  • 2021-01-06 05:21

    Have a look at the junitparams project, especially this example. It will show you how to use a CSV file for parameter input. Here's a short example:

    My test.csv file:

    1, one
    2, two
    3, three
    

    My test:

    package com.stackoverflow.sourabh.example;
    
    import static org.junit.Assert.assertTrue;
    import junitparams.FileParameters;
    import junitparams.JUnitParamsRunner;
    
    import org.junit.Test;
    import org.junit.runner.RunWith;
    
    @RunWith(JUnitParamsRunner.class)
    public class FileReadingParameterizedTest {
    
        @Test
        @FileParameters("src/test/resources/test.csv")
        public void testWithCSV(int number, String name) {
            assertTrue(name + " is not at least two", number >= 2);
        }
    
    }
    

    Obviously the first test will fail, producing the error message one is not at least two.

    0 讨论(0)
  • 2021-01-06 05:24
    @RunWith(JUnitParamsRunner.class)
    public class FileParamsTest {
    
        @Test
        @FileParameters("src/test/resources/test.csv")
        public void loadParamsFromFileWithIdentityMapper(int age, String name) {
            assertTrue(age > 0);
        }
    
    }
    

    JUnitParams has support for loading the data from a CSV file.

    CSV File will contain

    1,true
    2,false
    
    0 讨论(0)
  • 2021-01-06 05:35

    In Spring-boot Java framework, you can use the Value annotation conveniently within the class,

    @Component
    public class MyRunner implements CommandLineRunner {
    
    @Value("classpath:thermopylae.txt") //Annotation
    private Resource res; // res will hold that value the `txt` player
    
    @Autowired
    private CountWords countWords;
    
    @Override
    public void run(String... args) throws Exception {
    
        Map<String, Integer> words =  countWords.getWordsCount(res);
    
        for (String key : words.keySet()) {
    
            System.out.println(key + ": " + words.get(key));
           }
       }
    }
    

    Source

    0 讨论(0)
提交回复
热议问题