-2

I have created One Junit class Parent with Before and After Annotation. As I dont have access to change the parent and it is also must for me to Extends That Class Only.I Want to Avoid the Before and after for some of my Child Class TestCase.

Parent.class is in JAR1

public class Parent {
@Before
public void RunBefore_EveryTestCase()
{}
@After
public void RunAfter_EveryTestCase()
{}    

child.class is in JAR2

import Parent;
public class Child extends Parent{
@Test1        
 /////////////////I DONT Want to Run Before and After inherit From Parent
public void RunBefore_EveryTestCase()
{}
Hasnain Ali Bohra
  • 2,130
  • 2
  • 11
  • 25

1 Answers1

1

If you are extending the Parent class in your Child and you don't want to execute the implementation for @Before and @After in your child, just override those methods and annotate with @Before and @After and provide an empty implementation and don't call super method as well. That should solve your problem of not executing the parent implementation.

This is the parent Class

public class Parent {
   @Before
   public void before(){
       System.out.println("Parent Before");
   }

   @After
   public void after(){
       System.out.println("Parent After");
   } 
}

This is the Child Class

public class Child extends Parent {
   @Before
   public void before(){
       System.out.println("Child Before");
   }

   @After
   public void after(){
       System.out.println("Child After");
   }

   @Test
   public void test(){
       System.out.println("Running Test");
   }
}

Output:

Child Before
Running Test
Child After

So If you have an empty implementation of before and after methods in Child class then it will print only Running Test

Sampath
  • 599
  • 5
  • 12
  • Hi, As per the below link it didn't work for me. Can you suggest another approach to do it. [http://stackoverflow.com/questions/6076599/what-order-are-the-junit-before-after-called] – Hasnain Ali Bohra Mar 17 '17 at 06:51
  • Added the code that is tested. It works. Comment back if you still have any issue. – Sampath Mar 17 '17 at 08:48