Wednesday 27 June 2018

Junit: Run the test from main method

In my previous posts, I explained how to run the tests from Eclipse junit plugin. You can even run the test from main() method.

         public static void main(String args[]) {
         JUnitCore.main("com.sample.arithmetic.ArithmeticTest");
         }

Find the below working application.

Arithmetic.java
package com.sample.arithmetic;

public class Arithmetic {

 public int sum(int a, int b) {
  return a + b;
 }
 
}

ArithmeticTest.java
package com.sample.arithmetic;

import static org.junit.Assert.assertEquals;

import org.junit.Test;

/**
 * Test cases follow below naming convention. methodName_input_output format.
 * 
 * @author krishna
 *
 */
public class ArithmeticTest {

 private Arithmetic arithmetic = new Arithmetic();

 @Test
 public void add_10And5_15() {

  int expected = 15;
  int actual = arithmetic.sum(10, 5);

  assertEquals(expected, actual);
 }

 @Test
 public void add_10AndMinus5_5() {

  int expected = 5;
  int actual = arithmetic.sum(10, -5);

  assertEquals(expected, actual);
 }
}

TestApp.java

package com.sample.test;

import org.junit.runner.JUnitCore;

public class TestApp {
 public static void main(String args[]) {
  JUnitCore.main("com.sample.arithmetic.ArithmeticTest");
 }
}


When you ran TestApp.java, you can able to see below kind of messages in console.


Previous                                                 Next                                                 Home

No comments:

Post a Comment