Saturday, August 23, 2014

jUnit: Dynamic Tests Generation

Dynamic tests generation is useful when you need to run the same set of tests on many different input values or configurations. It can be achieved either using parametrized tests or using theories.

Theories are valuable when you have a bunch of data to be used as parameters and want to run tests on all their combinations. You get less control, but you do not have to write combining and iterating code by yourself. Basics about how theories work are explained on java code geeks (original at java advent calendar), so this post focus on parametrized tests.

Parametrized tests are better when you need to have good control over the input values, e.g. directory with files that are served as an input or a list of meaningful parameters combinations.

Parametrized Tests

Parametrized test is a test case able to accept parameters and a list of all parameter combinations you want it to run at. JUnit goes through the list of parameters, initializes the test case with each of them and then runs all its test methods.

Both GUI and Maven runners then interpret each parametrized test run as a separate test. If some of them fails, it is immediately clear which did failed and how many of them failed.

Example Use Case
Less4j is less to css compiler, so each of its tests is defined by an input less file and an expected css file. The compiler is run on input file and its output is compared to the expected css. If they match, test is passed.

All .less files are stored in a directory. Parametrized test case reads that directory and creates one jUnit test for each file. Therefore we can add new tests just by creating new .less and .css, run tests via "run all" button and see new test in all reports.

How to Use It
Parametrized test case must have following things:
  • a @RunWith(Parameterized.class) class annotation,
  • a constructor that accepts test case parameters,
  • a static method annotated with @Parameters to generate parameters,
  • test methods that runs on parameters supplied in constructor.

Constructor
Parametrized constructor must have at least one parameter. For example, the compiler test case can take input less as a first argument and expected compiled css as second argument. The third argument name is ignored and will be explained later:
@RunWith(Parameterized.class)
public class ParametrizedTest {

  public ParametrizedTest(String less, String expectedCss, String name) {
    this.less = less;
    this.expectedCss = expectedCss;
  }

}

Parameters
The static method generating parameters must return an implementation of the Iterable interface. The iterator returns arrays containing sets of parameters. Each array is used to create one test case instance and objects in it are used as constructor parameters.

For example, following method returns two arrays and thus leads to two test case instances:
@Parameters(name="Name: {2}")
public static Iterable<Object[]> generateParameters() {
  List<Object[]> result = new ArrayList<Object[]>();
  result.add(new Object[] {"less", "css", "pass"});
  result.add(new Object[] {"less", "error", "fail"});
  return result;
}

The name annotation parameter is optional. Its value will be shown in GUI or maven report as the test case name. The {n} is placeholder for n-th array value. They are indexed from 0, so the first test case will be named Name: pass and second test case will be named Name: fail.

Test Methods
Parametrized test case can have any number of tests and they must be annotated with @Test annotation:
@Test
public void testCss() { //dummy test method
  String actualCss = compile(less);
  assertEquals(expectedCss, actualCss);
}

@Test
public void testSourceMap() { //another test method
  String actualCss = compile(less);
  assertEquals(expectedCss, actualCss);
}

private String compile(String less) { //dummy compile method
  return "css"; 
}  

Output
If you run the above test class, the JUnit view will show following structure:
[F] com.github.sommeri.jUnit4Examples.ParametrizedTest
[ ] |-- [Name: pass]
[ ] |---------------- testCss[Name: pass] 
[ ] |---------------- testSourceMap[Name: pass] 
[F] |-- [Name: fail]
[F] |---------------- testCss[Name: fail] 
[F] |---------------- testSourceMap[Name: fail] 

Full Test Case
@RunWith(Parameterized.class)
public class ParametrizedTest {
  
  private String less;
  private String expectedCss;

  public ParametrizedTest(String less, String expectedCss, String name) {
    this.less = less;
    this.expectedCss = expectedCss;
  }
  
  @Parameters(name="Name: {2}")
  public static Iterable<Object[]> generateParameters() {
    List<Object[]> result = new ArrayList<Object[]>();
    result.add(new Object[] {"less", "css", "pass"});
    result.add(new Object[] {"less", "error", "fail"});
    return result;
  }
  
  @Test
  public void testCss() {
    String actualCss = compile(less);
    assertEquals(expectedCss, actualCss);
  }

  @Test
  public void testSourceMap() {
    String actualCss = compile(less);
    assertEquals(expectedCss, actualCss);
  }

  //dummy compile method
  private String compile(String less) {
    return "css"; 
  }  
}

More About jUnit

Following post about jUnit 4 features:

48 comments:

Unknown said...

thx!

SEO BACKLINKS said...

SEE MORE ARTICLE IN HERE. CLICK IN HERE

shivani said...

A bewildering web journal I visit this blog, it's unfathomably heavenly. Oddly, in this present blog's substance made the purpose of actuality and reasonable. The substance of data is informative
Oracle Fusion Financials Online Training
Oracle Fusion HCM Online Training
Oracle Fusion SCM Online Training

Rainbow Training Institute said...

Thanks for sharing valuable article having good information and also gain worth-full knowledge.

Oracle ICS Online Training

Rainbow Training Institute said...

Thank you for sharing your awesome and valuable article this is the best blog for the students they can also learn.

Workday Online Training

Robert said...

Having an assignment due tomorrow and understand you can’t do it yourself? But you’re afraid of delegating your paper to some scam services as well? Why not check https://scamfighter.net/review/99papers.com on Scamfighter.net

shivani said...


Brilliant blog I visit this blog it's incredibly awesome. Curiously, in this blog content formed doubtlessly and sensible. The substance of information is helpful.
Oracle Fusion HCM Online Training
Oracle Fusion SCM Online Training
Oracle Fusion Financials Online Training
Oracle Fusion HCM Training In Hyderabad
Oracle Fusion SCM Training In Hyderabad
Oracle Fusion Financials Training In Hyderabad
oracle fusion financials classroom training
Oracle Fusion HCM Classroom Training
oracle cpq online training / Oracle CPQ Class Room Training
Oracle Taleo Online Training

shivani said...

An overwhelming web journal I visit this blog, it's unfathomably amazing. Unusually, in this present blog's substance made inspiration driving truth and reasonable. The substance of data is enlightening
Oracle Fusion Financials Online Training
Oracle Fusion HCM Online Training
Oracle Fusion SCM Online Training

jose said...

Really nice post. Thank you for sharing amazing information.
Java Training in Credo Systemz/Java Training in Chennai Credo Systemz/Java Training in Chennai/Java Training in Chennai with Placements/Java Training in Velachery/Java Training in OMR/Java Training Institute in Chennai/Java Training Center in Chennai/Java Training in Chennai fees/Best Java Training in Chennai/Best Java Training in Chennai with Placements/Best Java Training Institute in Chennai/Best Java Training Institute near me/Best Java Training in Velachery/Best Java Training in OMR/Best Java Training in India/Best Online Java Training in India/Best Java Training with Placement in Chennai

Unknown said...

data sgp
data sydney
datahk
syair sydney
syairsgp
datasgp
paito warna
http://warungsgp.com/
live hk 6d
live sydney

Chandra Sekhar Reddy said...

Excellent Information
Yaaron Studios is one of the rapidly growing editing studios in Hyderabad. We are the best Video Editing services in Hyderabad. We provides best graphic works like logo reveals, corporate presentation Etc. And also we gives the best Outdoor/Indoor shoots and Ad Making services.
Best video editing services in Hyderabad,ameerpet
Best Graphic Designing services in Hyderabad,ameerpet­
Best Ad Making services in Hyderabad,ameerpet­

Chandra Sekhar Reddy said...

Nice Post
"Pressure Vessel Design Course is one of the courses offered by Sanjary Academy in Hyderabad. We have offer professional
Engineering Course like Piping Design Course,QA / QC Course,document Controller course,pressure Vessel Design Course,
Welding Inspector Course, Quality Management Course, #Safety officer course."
Piping Design Course in India­
Piping Design Course in Hyderabad
QA / QC Course
QA / QC Course in india
QA / QC Course in Hyderabad
Document Controller course
Pressure Vessel Design Course
Welding Inspector Course
Quality Management Course
Quality Management Course in india
Safety officer course

Tour My Pakistan said...

Nice post
Naran is one of the Beautiful destination for the holiday. Book Naran tour packages at Tour My Pakistan at best price.

Reena said...

Thanks for provide great informatic and looking beautiful blog, really nice required information & the things i never imagined and i would request, wright more blog and blog post like that for us. Thanks you once agian

court marriage in delhi ncr
court marriage in delhi
court marriage in noida
court marriage in ghaziabad
court marriage in gurgaon
court marriage in faridabad
court marriage in greater noida
name change online
court marriage in chandigarh
court marriage in bangalore

jimijhonbrow said...

Wow! this is Amazing! Do you know your hidden name meaning ? Click here to find your hidden name meaning

Unknown said...

If you're looking to lose kilograms then you absolutely have to jump on this totally brand new custom keto meal plan diet.

To design this keto diet service, certified nutritionists, personal trainers, and top chefs united to develop keto meal plans that are effective, suitable, cost-efficient, and satisfying.

Since their launch in early 2019, hundreds of clients have already transformed their figure and health with the benefits a smart keto meal plan diet can give.

Speaking of benefits: in this link, you'll discover eight scientifically-tested ones offered by the keto meal plan diet.

Muhammad said...

I have read so many articles regarding the blogger lovers
however this article is, in fact, a pleasant piece of writing, keep it up Rent a jeep Prado in Pakistan

Muhammad said...

It is really a great and useful piece of info. I’m glad that you shared this helpful info with us.From
Rent a Car in Islamabad

Dakota Leest said...

Hi there. Very interesting article. I need help with writing dissertation results section. I know I'm getting it. I have asked writers many times. I am glad that I have experience that helps me always find the right way to solve problems.

megan collins said...

Thanks for sharing this great information I am impressed by the information that you have on this blog. Same as your blog i found another one oracle fusion product hub. Actually, I was looking for the same information on internet for
Oracle taleo tutorial and came across your blog. I am impressed by the information that you have on this blog. It shows how well you understand this subject, you can learn more about Oracle CPQ BML Tutorial also.

Gregor Brown said...

How often do you use additional information? I want to tell you about plagiarism facts https://theplagiarism.com/articles/plagiarism-facts. I always check my essay for plagiarism. It helps to have the best scientific work.

Jeffrey said...

Get expert help from leading writers! https://exclusivethesis.com/writing-a-legal-brief/ will help you with any writing work.

Quickbooks Expert said...

Nice & Informative Blog !
To fix such issue, you must contact our experts via QuickBooks Support Number 1-855-652-7978 and get permanent ways to solve QuickBooks problems. Our team consists of highly qualified professionals who provide the best ways to troubleshoot QuickBooks problems.

William said...

Hey!Amazing work. With full of knowledge. Our Team resolve any glitches occurring while utilizing the software. Looking for QuickBooks Phone Number Contact us +1-855-756-1077.Our experts will assist you to fulfil your accounting needs. The solutions are accurate and time-saving.

Quickbooks Expert said...

Nice post!

Worried About QuickBooks Error ?Get in touch with QuickBooks expert for instant solution.
Click Here to know how to fix QuickBooks Error 12152

Dial on QuickBooks Error Support Number +1-855-977-7463.

Lauren Kathy said...

Hey! Excellent work. Being a QuickBooks user, if you are struggling with any issue, then dial QuickBooks Customer Service Number. Our team at QuickBooks will provide you with the best technical solutions for QuickBooks problems.

Emily Green said...

Hey! Well-written blog. It is the best thing that I have read on the internet today. Moreover, if you are looking for the solution of QuickBooks Software, visit at QuickBooks Customer Service Number to get your issues resolved quickly.

Rhys Faulkner said...

I loved the post, keep posting interesting posts. I will be a regular reader
Rently

Simmyjessure said...

Its so amazing article with nicnfomative information you can get also QuickBooks get solution at

Quickbooks Phone Number

daisydavis said...

This is very informative information. QuickBooks is an accounting regarding QuickBooks software then you van connect me at quickbooks phone number

North Carolina said...

Call us on Quickbooks Phone Number 1855-756-1077 to get targeted services

Minnesota said...

Our team at Quickbooks Phone Number 1833-244-5865 is responsible to make sure that particular issue should be discarded in the quickest time. Here you will receive permanent solutions to QuickBooks issues.

Arizona said...

Get immediate assistance for QuickBooks errors on
Quickbooks Phone Number1 877-948-5867.

Simmyjessure said...

i m very happy read your informative and knowledgeable blog thanks for provide useful information i have also share your information other planform . we also provide Quickbooks solution you can call at
quickbooks phone number

alexa jone said...

Excellent blog .Thanks For Sharing with us contact at quickbooks phone number for any quickboooks issue

wy983450 said...

if you have any queries. It’s always recommended to use the corporate number as it is normally the quickest way to get in touch with a representative.We provide 24*7 technical assistance for quickbooks customer service (866)447-5478

North Carolina said...

Fall back on a professional to solve quickbooks error 15215 for best service Quickbooks Phone Number 1 855-756-1077

Unknown said...

Reach to the customer service team via phone, emails, chat and get the best solution to the error occurred. Call us quickbooks customer service (888) 272-4881

Ohio said...

QuickBooks the simplest, cheapest accounting software that has made accounting life easier and when it itself gets in trouble then we have a team of experts to help you resolve issues with QuickBooks. You can also feel free to contact us if you have any queries or need assistance in resolving the issueQuickBooks expert (855) 377-7767

Minnesota said...

If you have QuickBooks errors or problems that are slowing down your business? QuickBooks Customer Service Number is here to help. We have a team of experienced professionals who will be more than happy to solve any issue that you may have in the shortest time possible.
quickboks customer service(855) 742-7868.

Sarika said...

Thanks for sharing this blog. The content is beneficial and useful. Very informative post. We are also providing the best services click on below links to visit our website.

Oracle Fusion HCM Training
Workday Training
Okta Training
Palo Alto Training
Adobe Analytics Training

Phoebe Geller said...

Hey! Nice Blog, I have been using QuickBooks for a long time. One day, I encountered QuickBooks Customer Service in my software, then I called QuickBooks Support Phone Number (855)552-2543. They resolved my error in the least possible time.

Simmyjessure said...

Very Interesting blog Thanks For Sharing if You are using QuickBooks accounting software For business purpose and facing some issueVery Interesting blog Thanks For Sharing if You are using QuickBooks accounting software For business purpose and facing some issue then just call at Quickbooks Customer Service Number(877) 603-0806

Nick mosan said...

The QuickBooks error 15241 can be extremely inconvenient for the user. This issue is generally accompanied by the message “The payroll update failed to finish successfully.” It can occur as a result of a corrupted Microsoft Windows installer or a corrupted QuickBooks desktop installation.

Quickbooks Customer Service said...


Hiiii!!
If you are looking for Quickbooks Customer Service you can reach us at.+1 855-786-5155,NH.

car rental near me said...

Thanks for sharing very useful information with us it’s a great post. In Pakistan driving rules are so strict in some cities. Safety is so important specifically when you are driving in Karachi, Lahore and Islamabad for this purpose kindly follow driving rules properly always beneficial for avoiding so many certain or un-certain risks.

wedding car rental karachi

car rental near me said...
This comment has been removed by the author.
DXB said...

DXB offer best discounted rate for Location Voiture Dubai.

Post a Comment