4

API の単体テストにパラメーター化されたテストを使用することについて質問があります。今のような配列リストを構築する代わりに

Arrays.asList(new Object[]{
   {1},{2},{3}
});

ファイル内の行を1行ずつ読み取り、スペースを分割して配列に入力したい。このようにして、すべてが一般化されます。誰かがそのような方法を例で提案できますか?

また、さまざまな引数をプライベート メンバーとして宣言し、テスト ユニットのコンストラクターで初期化せずにテストできる方法はありますか?

編集:ダンカンが尋ねたコード

@RunWith(Parameterized.class)
public class JunitTest2 {

    SqlSession session;
    Integer num;
    Boolean expectedResult;
    static BufferedInputStream buffer = null;

    public JunitTest2(Integer num, Boolean expected){
        this.num = num;
        this.expectedResult = expected;
    }

    @Before
    public void setup() throws IOException{
        session = SessionUtil.getSqlSessionFactory(0).openSession();
        SessionUtil.setSqlSession(session);
        buffer = new BufferedInputStream(getClass().getResourceAsStream("input.txt"));
        System.out.println("SETUP!");
    }

    @Test
    public void test() {
        assertEquals(expectedResult, num > 0);
        System.out.println("TESTED!");
    }

    @Parameterized.Parameters
    public static Collection getNum() throws IOException{
        //I want my code to read input.txt line by line and feed the input in an arraylist so that it returns an equivalent of the code below

        return Arrays.asList(new Object[][]{
            {2, true},
            {3, true},
            {-1, false}
        });
    }
    @After
    public void tearDown() throws IOException{
        session.close();
        buffer.close();
        System.out.println("TEARDOWN!");
    }
}

また、私のinput.txtは次のようになります:

2 true
3 true
-1 false
4

3 に答える 3

14
@RunWith(JUnitParamsRunner.class)
public class FileParamsTest {

    @Test
    @FileParameters("src/test/resources/test.csv")
    public void loadParamsFromFileWithIdentityMapper(int age, String name) {
        assertTrue(age > 0);
    }

}

JUnitParamsは、CSV ファイルからのデータのロードをサポートしています。

CSV ファイルには以下が含まれます

1,true
2,false
于 2014-01-28T09:58:45.897 に答える
1

ValueSpring-boot Java フレームワークでは、クラス内でアノテーションを便利に使用できます。

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

ソース

于 2020-06-27T12:58:05.553 に答える