JMeter: Read CSV file contents into JUnit testcase

2019-03-01 18:28发布

问题:

I want to use data from CSV file mentioned in CSV Data Set Config of JMeter into my JUnit testcase program and pass that data to test method.

I know how to get data from CSV Data Set Config for HTTP Request but couldn't find any help for JUnit Request.

My test method is:

public void test() throws IOException{

        try {
            CheckUser(UserId);//I want to get this UserId from CSV file mentioned in CSV Data Set Config of JMeter
        }catch (Exception e) {
            e.printStackTrace();
            fail();  
        }
}

I am new to JUnit and JMeter. Any help on this would be greatly appreciated. Thanks.

回答1:

You can try using:

 JMeterContextService.getContext().getVariables().get("varName") 

see:

  • https://jmeter.apache.org/api/org/apache/jmeter/threads/JMeterContext.html#getVariables()

  • https://jmeter.apache.org/api/org/apache/jmeter/threads/JMeterContext.html



回答2:

Finally I found solution using:

JUnitSampler junitSampler=new JUnitSampler(); String UserId=junitSampler.getThreadContext().getVariables().get("userId");

Now my JUnit testcase program is accepting UserId from CSV file mentioned in CSV Data Set Config.

Thanks PMD UBIK-INGENIERIE and Dmitri T for your help.



回答3:

The answer by PMD UBIK-INGENIERIE is correct and should work.

Make sure that your userId variable is set and is not null via i.e. Debug Sampler and View Results Tree listener combination.

Also remember that JMeter Variables scope is limited to current thread group only, if you want to use values from another thread group you need to convert JMeter Variables to JMeter Properties which have global scope. See Knit One Pearl Two: How to Use Variables in Different Thread Groups for more details.

You can refer a property as follows:

JMeterContextService.getContext().getCurrentSampler().getPropertyAsString("userId") 


标签: csv junit jmeter