How to make JUnit test cases execute in parallel? [duplicate] - junit

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Running junit tests in parallel?
I found the test cases inside jUnit are executed in sequence, how to make them execute in parallel?

Junit4 provides parallel feature using ParallelComputer:
public class ParallelComputerTest {
#Test
public void test() {
Class[] cls={ParallelTest1.class,ParallelTest2.class };
//Parallel among classes
JUnitCore.runClasses(ParallelComputer.classes(), cls);
//Parallel among methods in a class
JUnitCore.runClasses(ParallelComputer.methods(), cls);
//Parallel all methods in all classes
JUnitCore.runClasses(new ParallelComputer(true, true), cls);
}
public static class ParallelTest1 {
#Test public void a(){}
#Test public void b(){}
}
public static class ParallelTest2 {
#Test public void a(){}
#Test public void b(){}
}
}

Here is some sample code. This works for me really well. ExecutorService.
public class TestCases {
static ExecutorService exe ;
public static void main(String[] args) throws Throwable {
test1() ;
test2() ;
test3() ;
}
public static void test1() {
exe = Executors.newCachedThreadPool() ;
for (int i = 0 ; i < 10 ; i++) {
Test1 test1 = new Test1() ;
exe.execute(test1) ;
}
exe.shutdown() ;
while(!exe.isShutDown()) {
}
}
//same for test2 and test3
}
public class Test1 implements Runnable {
public Test1() {
}
#Test
public myTest throws Throwable {
}
}

Related

Junit Test (Mockito, PowerMock) a class with void method and private value

some sample code like:
(I just added some more details)
public class A {
#Autowired
private Data data;
#RequestMapping(value="/Boo", method = RequestMethod.GET)
public void Boo(){
data.someMethod();
}
}
I want to test the someMethod() is run or not.
I have tried #First answer but got some error message like below:
java.lang.AbstractMethodError: org.powermock.api.mockito.internal.exceptions.StackTraceCleanerProvider$1.isIn(Ljava/lang/StackTraceElement;)Z
at org.mockito.internal.exceptions.stacktrace.StackTraceFilter.filter(StackTraceFilter.java:33)
at org.mockito.internal.exceptions.stacktrace.ConditionalStackTraceFilter.filter(ConditionalStackTraceFilter.java:23)
at org.mockito.exceptions.base.MockitoException.filterStackTrace(MockitoException.java:44)
#RunWith(MockitoJUnitRunner.class)
public class ATest {
#InjectMocks
private A a;
#Spy
private Data data;
#Test
public void test() {
// execute
this.a.Boo();
// verify
Mockito.verify(this.data).someMethod();
}
}

How to mock a void method with no arguments?

For Example:
Class A{
string s = null;
public void method(){
s="Sample String";
}
}
I have a void method with similar scenario. How can I test such void method?
With void methods you should test the interaction with its dependent objects within the void method. I think a void method with no argument is rarely useful to test (but if you have a valid use case, please add it to your question). I provided you a simple example for a method with an argument but void as a return type:
public class A {
private DatabaseService db;
private PaymentService payment;
// constructor
public void doFoo() {
if(n < 2) {
db.updateDatabase();
} else {
payment.payBill();
}
}
}
And the unit test for this can look like the following
#RunWith(MockitoJUnitRunner.class)
public class ATest {
#Mock
DatabaseService db;
#Mock
PaymentService payment;
#Test
public void testDoFooWithNGreaterTwo() {
A cut = new A(db, payment); // cut -> class under test
cut.doFoo(3);
verify(payment).payBill(); // verify that payment was called
}
#Test
public void testDoFooWithNLessThanTwo() {
A cut = new A(db, payment); // cut -> class under test
cut.doFoo(1);
verify(db).updateDatabase(); // verify that db was called
}
}

Different behaviour for NullPointerException and IllegalAccessException

I am trying to understand throws clause in JAVA , I wrote the following
piece of code:
class check
{
static void demo()
{
System.out.println("Hello\n");
throw new IllegalAccessException("demo");
}
public static void main(String args[])
{
demo();
}
}
I understand that it won't compile as the exception has to be handled
in the main method and demo() should be defined with specifying a throws
clause for IllegalAccessException.
But when I change the exception to NullPointerException, the same
program compiles and executes:
class check
{
static void demo()
{
System.out.println("Hello\n");
throw new NullPointerException("Demo");
}
public static void main(String args[])
{
demo();
}
}

Test play controller with session data

I have a simple controller test.
route(fakeRequest(routes.Accounts.accounts()).session("sessionref","fakeSession"));
Secured Autheticator looks like this:
public class Secured extends play.mvc.Security.Authenticator {
#Inject
AuthServices authService;
public String getUsername(Http.Context context) {
return authService.checkSession(context);
}
#Override
public Result onUnauthorized(Http.Context context) {
return ok(index.render(formFactory.form(forms.LoginForm.class)));
}
}
How can i mock authService?
I tried to mock with guice bind but this method don't work
#Before
public void setup() {
startPlay();
MockitoAnnotations.initMocks(this);
Module testModule = new AbstractModule() {
#Override
public void configure() {
bind(AuthServices.class)
.toInstance(authServices);
}
};
GuiceApplicationBuilder builder = new GuiceApplicationLoader()
.builder(new play.ApplicationLoader.Context(Environment.simple()))
.in(Mode.TEST)
.overrides(testModule);
Guice.createInjector(builder.applicationModule()).injectMembers(this);
}
You can read this for testing Play controllers and follow this example for testing with Guice.
For your case it is something like this:
public class MyTest extends WithApplication {
#Mock
AuthServices mockAuthService;
#Override
protected Application provideApplication() {
return new GuiceApplicationBuilder()
.overrides(bind(CacheProvider.class).toInstance(mockAuthService))
.in(Mode.TEST)
.build();
}
#Before
public void setup() {
MockitoAnnotations.initMocks(this);
}
#Test
public void testAccounts() {
running(provideApplication(), () -> {
RequestBuilder testRequest = Helpers.fakeRequest(controllers.routes.Accounts.accounts()).session("sessionref","fakeSession");
Result result = route(testRequest);
//assert here the expected result
});
}
}

Run a list of jUnit runners

I have some test suites that in essence looks like
#Test
public void test1_2() {
test(1,2);
}
#Test
public void test1_3() {
test(1,3);
}
#Test
public void test4_5() {
test(4,5);
}
#Test
public void test4_9() {
test(4,9);
}
// and so forth
private void test(int i, int j) throws AssertionError{
// ...
}
(This is not the actual tests, but the essence, each #Test method only calls one method)
So my thinking was that I could use #RunWith for a custom BlockJUnit4ClassRunner which accepts a List of jUnit Runners.
How would this be achived? Or is there a better way to do it?
Why not use #Parameter ?
#RunWith(Parameterized.class)
public class YourTest{
private int i;
private int j;
public Parameter(int i, int j) {
this.i= i;
this.j= j;
}
#Parameters
public static Collection<Object[]> data() {
Object[][] data = new Object[][] { { 1, 2 }, { 1,3 }, { 4,5 }, { 4,9 } };
return Arrays.asList(data);
}
#Test
public void test() throws InterruptedException {
//use i & j
}
}
This looks to me like something that should be done with Theories. Otherwise, you could use Enclosed to have multiple inner classes each with its own runner.