how to use multicore in a junit test code example

Example 1: parallel testing in junit

To run parallel testing in Junit
We are using maven-surefire plugin
in pom.xml file.
We can specify how many threads we
want to run as at the same time.

We also have to make some changes 
in Driver class. We need to use 
"ThreadLocal<WebDriver> instead of
"WebDriver" Because "WebDriver" 
generates only a single WebDriver object, 
but "ThreadLocal<WebDriver>" generates
multiple browser to run parallel testing.


 <testFailureIgnore>TRUE</testFailureIgnore>
     <parallel>METHODS</parallel>
     <threadCount>40</threadCount> 
     <forkCount>2C</forkCount>
     <perCoreThreadCount>false</perCoreThreadCount>
     <include>**/*Runner*.java</include>

*Runner* - any test class Contains Runner
 Runner* - any test class starts with Runner
*Runner  - any test class ends with Runner 

PerCoreThreadCount: set false it will
try to match number of threads with number
of CPU cores. Regardsless on threadCount value.

Example 2: junit parallel testing

If we use JUNIT, we can use maven plugins to run tests in parallel. 
In maven-surefire-plugin, we can specify how many threads we want to open 
at the same time.

<plugin>
	<groupId>org.apache.maven.plugins</groupId>
	<artifactId>maven-surefire-plugin</artifactId>
	<version>2.18.1</version>
	<configuration>
		<parallel>classes</parallel>  ==> you can choose classes or methods
		<threadCount>5</threadCount>  ==> how many browser will be launched
			<includes>					  
				<includetest1.java</include>   
				<includetest2.java</include>
				<includetest3.java</include>
				<includetest4.java</include>
			</includes>
		<testFailureIgnore>true</testFailureIgnore>
	</configuration>
</plugin>

We also have to make some changes in Driver class. We need to use 
"ThreadLocal<WebDriver> driverPool" instead of "WebDriver driver". 
Because "WebDriver" generates only a single WebDriver object, 
whereas "ThreadLocal<WebDriver>" generates multiple browser to run 
parallel testing.  

In TestNG it is very easy and efficient to perform

Tags:

Java Example