有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

JavaCSV解析,逐行读取Junit测试的输入

这是我的代码,用于逐行读取csv文件以执行HTTP请求的Junit测试。但我只能测试备用数据,即:从CSV文件中读取第一个数据,然后跳过第二个数据,然后读取第三个数据,然后跳过第四个数据等等,如果有任何问题,请帮助我处理代码

package testingpack;

import static org.junit.Assert.*;


import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;

import com.csvreader.CsvReader;
import java.io.UnsupportedEncodingException;

import org.codehaus.jettison.json.JSONException;
import org.codehaus.jettison.json.JSONObject;
import org.junit.Test;


public class testcase {

@Test
public void test() throws UnsupportedEncodingException, JSONException {

    String output = null;
    String url="";
    String testJson;
    int c=0;
    try {
        CsvReader reader = new CsvReader(new FileReader("C:\\Users\\Srijan Rana\\Desktop\\Api.csv"), ',');


while(reader.readRecord())
{
    c=c+1;
    System.out.println("Loop Counter"+c);
    Boolean br = reader.readRecord();

        if (br) {
            String[] columns = reader.getValues();
            url=columns[1];
            System.out.println("The URL is \n"+url);    
            testJson=columns[3];
            testJson=testJson.replaceAll("~", ",");

        System.out.print(testJson);

            if(columns[2].equalsIgnoreCase("POST"))

                output=(String) CommonUtil.postDataToService(url, testJson);
                else if(columns[2].equalsIgnoreCase("Get"))
                     output=(String) CommonUtil.getResponseFromService(url);


                System.out.println("Output is: "+output);
                JSONObject json = new JSONObject(output);

                String val = json.getString("mobile_exist");

               assertEquals("false",val);

    }

}
    } catch (FileNotFoundException fe) {
        System.out.println(fe.getMessage());

    } catch (IOException ie) {
        System.out.println(ie.getMessage());
}

}
}

共 (3) 个答案

  1. # 1 楼答案

    问题是您正在使用readRecord两次。所以第一次读第一行,第二次读第二行。这意味着您正在处理替代行

    示例代码

    try {
    
            CsvReader reader= new CsvReader(file);
    
            while (reader.readRecord())
            {
                // logic goes here
            }
    
            reader.close();
    
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    
  2. # 2 楼答案

    修改代码如下:

    boolean br = reader.readRecord();
    while(br)
    {
        ...
        ... // remove 2nd call of `readRecord` and `if` condition
        ...
        ...
        br = reader.readRecord() // should be last line in while loop
    }
    
  3. # 3 楼答案

    Boolean br = reader.readRecord();   
    while(br)
    {
        br = reader.readRecord();
        //code
    }
    

    这是对我有用的代码。谢谢你的帮助