Mocking Superclass method call - java

I want to test a class, which extends a superclass. I use JUnit and Mockito. In one method this class calls a supermethod of the superclass:
#Override
public void init(String input){
super.init();
...
}
Now in my test-class I already have following setup:
#InjectMocks
private MyClass classUnderTest = new MyClass();
#Before
public void setUp(){
MockitoAnnotations.initMocks(this);
}
Now how do I mock the super.method call? I don't think Spying will help in this case.

You should not be mocking this call. You should not have inheritance here at all. If class A needs to call method b() which is tested elsewhere and you don't care about what it does, it means that method b() should be in class B which is a dependency of class A - and then you can do dependency injection and mock B.
If this is some legacy code that you cannot change, one of interesting strategies of refactoring it is making a new method in class A and overriding it in your test (by either extending A or spying on this method):
class A extends B {
private void b() {
// something here
super_b();
}
protected void super_b() {
super.b();
}
}

Related

Mockito to throw exception when calling super method [duplicate]

I'm using Mockito in some tests.
I have the following classes:
class BaseService {
public void save() {...}
}
public Childservice extends BaseService {
public void save(){
//some code
super.save();
}
}
I want to mock only the second call (super.save) of ChildService. The first call must call the real method. Is there a way to do that?
If you really don't have a choice for refactoring you can mock/stub everything in the super method call e.g.
class BaseService {
public void validate(){
fail(" I must not be called");
}
public void save(){
//Save method of super will still be called.
validate();
}
}
class ChildService extends BaseService{
public void load(){}
public void save(){
super.save();
load();
}
}
#Test
public void testSave() {
ChildService classToTest = Mockito.spy(new ChildService());
// Prevent/stub logic in super.save()
Mockito.doNothing().when((BaseService)classToTest).validate();
// When
classToTest.save();
// Then
verify(classToTest).load();
}
No, Mockito does not support this.
This might not be the answer you're looking for, but what you're seeing is a symptom of not applying the design principle:
Favor composition over inheritance
If you extract a strategy instead of extending a super class the problem is gone.
If however you are not allowed to change the code, but you must test it anyway, and in this awkward way, there is still hope. With some AOP tools (for example AspectJ) you can weave code into the super class method and avoid its execution entirely (yuck). This doesn't work if you're using proxies, you have to use bytecode modification (either load time weaving or compile time weaving). There are be mocking frameworks that support this type of trick as well, like PowerMock and PowerMockito.
I suggest you go for the refactoring, but if that is not an option you're in for some serious hacking fun.
Consider refactoring the code from ChildService.save() method to different method and test that new method instead of testing ChildService.save(), this way you will avoid unnecessary call to super method.
Example:
class BaseService {
public void save() {...}
}
public Childservice extends BaseService {
public void save(){
newMethod();
super.save();
}
public void newMethod(){
//some codes
}
}
I found a way to suppress the superclass method using PowerMockito. 3 simple steps need for this
Use PowerMockito.suppress method and MemberMatcher.methodsDeclaredIn method to supress parent class method
Second add Parent class in #PrepareForTest
Run your test class with PowerMock ie add #RunWith(PowerMockRunner.class) above your test class.
#RunWith(PowerMockRunner.class)
#PrepareForTest({BaseService.class})
public class TestChildService(){
#Spy
private ChildService testChildServiceObj = Mockito.spy(new ChildService());
#Test
public void testSave(){
PowerMockito.suppress(MemberMatcher.methodsDeclaredIn(BaseService.class));
//your further test code
testChildServiceObj.save();
}
}
Note: This will work only when the superclass method does not return anything.
Maybe the easiest option if inheritance makes sense is to create a new method (package private??) to call the super (lets call it superFindall), spy the real instance and then mock the superFindAll() method in the way you wanted to mock the parent class one. It's not the perfect solution in terms of coverage and visibility but it should do the job and it's easy to apply.
public Childservice extends BaseService {
public void save(){
//some code
superSave();
}
void superSave(){
super.save();
}
}
create a package protected (assumes test class in same package) method in the sub class that calls the super class method and then call that method in your overridden sub class method. you can then set expectations on this method in your test through the use of the spy pattern. not pretty but certainly better than having to deal with all the expectation setting for the super method in your test
Even if i totally agree with iwein response (
favor composition over inheritance
), i admit there are some times inheritance seems just natural, and i don't feel breaking or refactor it just for the sake of a unit test.
So, my suggestion :
/**
* BaseService is now an asbtract class encapsulating
* some common logic callable by child implementations
*/
abstract class BaseService {
protected void commonSave() {
// Put your common work here
}
abstract void save();
}
public ChildService extends BaseService {
public void save() {
// Put your child specific work here
// ...
this.commonSave();
}
}
And then, in the unit test :
ChildService childSrv = Mockito.mock(ChildService.class, Mockito.CALLS_REAL_METHODS);
Mockito.doAnswer(new Answer<Void>() {
#Override
public Boolean answer(InvocationOnMock invocation)
throws Throwable {
// Put your mocked behavior of BaseService.commonSave() here
return null;
}
}).when(childSrv).commonSave();
childSrv.save();
Mockito.verify(childSrv, Mockito.times(1)).commonSave();
// Put any other assertions to check child specific work is done
You can do this with PowerMockito and replace behavior only of the parent class method with continuing testing the child's class method. Even when the method is returning some value, lets say a string, you can do something like this:
#RunWith(PowerMockRunner.class)
#PrepareForTest({ BaseService.class })
public class TestChildService() {
private BasicService basicServiceObj;
private ChildService testee;
#Before
public void init() throws Exception {
testee = new ChildService();
basicServiceObj = PowerMockito.spy(new BaseService());
PowerMockito.doReturn("Result").when(basicServiceObj, "save", ... optionalArgs);
}
#Test
public void testSave(){
testee.save();
}
}
If you are returning nothing (void) then instead of doReturn you can use doNothing. Add some optionalArgs if the method have some arguments, if not, then skip that part.
The reason is your base class is not public-ed, then Mockito cannot intercept it due to visibility, if you change base class as public, or #Override in sub class (as public), then Mockito can mock it correctly.
public class BaseService{
public boolean foo(){
return true;
}
}
public ChildService extends BaseService{
}
#Test
#Mock ChildService childService;
public void testSave() {
Mockito.when(childService.foo()).thenReturn(false);
// When
assertFalse(childService.foo());
}
There is simple approach that works for most of cases. You can spy your object and stub the method you want to mock.
Here is an example:
MyClass myObjectSpy = Mockito.spy(myObject);
org.mockito.Mockito.doReturn("yourReturnValue").when(mySpyObject).methodToMock(any()..);
So, when you test your object, you can use myObjectSpy and when methodToMock is called, it will overwrite the normal behavior by a mock method.
This code for a method with return. In case you have a void method you can use doNothing instead.

How to mock super class by Mockito / PowerMockito? [duplicate]

I'm using Mockito in some tests.
I have the following classes:
class BaseService {
public void save() {...}
}
public Childservice extends BaseService {
public void save(){
//some code
super.save();
}
}
I want to mock only the second call (super.save) of ChildService. The first call must call the real method. Is there a way to do that?
If you really don't have a choice for refactoring you can mock/stub everything in the super method call e.g.
class BaseService {
public void validate(){
fail(" I must not be called");
}
public void save(){
//Save method of super will still be called.
validate();
}
}
class ChildService extends BaseService{
public void load(){}
public void save(){
super.save();
load();
}
}
#Test
public void testSave() {
ChildService classToTest = Mockito.spy(new ChildService());
// Prevent/stub logic in super.save()
Mockito.doNothing().when((BaseService)classToTest).validate();
// When
classToTest.save();
// Then
verify(classToTest).load();
}
No, Mockito does not support this.
This might not be the answer you're looking for, but what you're seeing is a symptom of not applying the design principle:
Favor composition over inheritance
If you extract a strategy instead of extending a super class the problem is gone.
If however you are not allowed to change the code, but you must test it anyway, and in this awkward way, there is still hope. With some AOP tools (for example AspectJ) you can weave code into the super class method and avoid its execution entirely (yuck). This doesn't work if you're using proxies, you have to use bytecode modification (either load time weaving or compile time weaving). There are be mocking frameworks that support this type of trick as well, like PowerMock and PowerMockito.
I suggest you go for the refactoring, but if that is not an option you're in for some serious hacking fun.
Consider refactoring the code from ChildService.save() method to different method and test that new method instead of testing ChildService.save(), this way you will avoid unnecessary call to super method.
Example:
class BaseService {
public void save() {...}
}
public Childservice extends BaseService {
public void save(){
newMethod();
super.save();
}
public void newMethod(){
//some codes
}
}
I found a way to suppress the superclass method using PowerMockito. 3 simple steps need for this
Use PowerMockito.suppress method and MemberMatcher.methodsDeclaredIn method to supress parent class method
Second add Parent class in #PrepareForTest
Run your test class with PowerMock ie add #RunWith(PowerMockRunner.class) above your test class.
#RunWith(PowerMockRunner.class)
#PrepareForTest({BaseService.class})
public class TestChildService(){
#Spy
private ChildService testChildServiceObj = Mockito.spy(new ChildService());
#Test
public void testSave(){
PowerMockito.suppress(MemberMatcher.methodsDeclaredIn(BaseService.class));
//your further test code
testChildServiceObj.save();
}
}
Note: This will work only when the superclass method does not return anything.
Maybe the easiest option if inheritance makes sense is to create a new method (package private??) to call the super (lets call it superFindall), spy the real instance and then mock the superFindAll() method in the way you wanted to mock the parent class one. It's not the perfect solution in terms of coverage and visibility but it should do the job and it's easy to apply.
public Childservice extends BaseService {
public void save(){
//some code
superSave();
}
void superSave(){
super.save();
}
}
create a package protected (assumes test class in same package) method in the sub class that calls the super class method and then call that method in your overridden sub class method. you can then set expectations on this method in your test through the use of the spy pattern. not pretty but certainly better than having to deal with all the expectation setting for the super method in your test
Even if i totally agree with iwein response (
favor composition over inheritance
), i admit there are some times inheritance seems just natural, and i don't feel breaking or refactor it just for the sake of a unit test.
So, my suggestion :
/**
* BaseService is now an asbtract class encapsulating
* some common logic callable by child implementations
*/
abstract class BaseService {
protected void commonSave() {
// Put your common work here
}
abstract void save();
}
public ChildService extends BaseService {
public void save() {
// Put your child specific work here
// ...
this.commonSave();
}
}
And then, in the unit test :
ChildService childSrv = Mockito.mock(ChildService.class, Mockito.CALLS_REAL_METHODS);
Mockito.doAnswer(new Answer<Void>() {
#Override
public Boolean answer(InvocationOnMock invocation)
throws Throwable {
// Put your mocked behavior of BaseService.commonSave() here
return null;
}
}).when(childSrv).commonSave();
childSrv.save();
Mockito.verify(childSrv, Mockito.times(1)).commonSave();
// Put any other assertions to check child specific work is done
You can do this with PowerMockito and replace behavior only of the parent class method with continuing testing the child's class method. Even when the method is returning some value, lets say a string, you can do something like this:
#RunWith(PowerMockRunner.class)
#PrepareForTest({ BaseService.class })
public class TestChildService() {
private BasicService basicServiceObj;
private ChildService testee;
#Before
public void init() throws Exception {
testee = new ChildService();
basicServiceObj = PowerMockito.spy(new BaseService());
PowerMockito.doReturn("Result").when(basicServiceObj, "save", ... optionalArgs);
}
#Test
public void testSave(){
testee.save();
}
}
If you are returning nothing (void) then instead of doReturn you can use doNothing. Add some optionalArgs if the method have some arguments, if not, then skip that part.
The reason is your base class is not public-ed, then Mockito cannot intercept it due to visibility, if you change base class as public, or #Override in sub class (as public), then Mockito can mock it correctly.
public class BaseService{
public boolean foo(){
return true;
}
}
public ChildService extends BaseService{
}
#Test
#Mock ChildService childService;
public void testSave() {
Mockito.when(childService.foo()).thenReturn(false);
// When
assertFalse(childService.foo());
}
There is simple approach that works for most of cases. You can spy your object and stub the method you want to mock.
Here is an example:
MyClass myObjectSpy = Mockito.spy(myObject);
org.mockito.Mockito.doReturn("yourReturnValue").when(mySpyObject).methodToMock(any()..);
So, when you test your object, you can use myObjectSpy and when methodToMock is called, it will overwrite the normal behavior by a mock method.
This code for a method with return. In case you have a void method you can use doNothing instead.

Exception : mockito wanted but not invoked, Actually there were zero interactions with this mock

I have interface
Interface MyInterface {
myMethodToBeVerified (String, String);
}
And implementation of interface is
class MyClassToBeTested implements MyInterface {
myMethodToBeVerified(String, String) {
…….
}
}
I have another class
class MyClass {
MyInterface myObj = new MyClassToBeTested();
public void abc(){
myObj.myMethodToBeVerified (new String(“a”), new String(“b”));
}
}
I am trying to write JUnit for MyClass. I have done
class MyClassTest {
MyClass myClass = new MyClass();
#Mock
MyInterface myInterface;
testAbc(){
myClass.abc();
verify(myInterface).myMethodToBeVerified(new String(“a”), new String(“b”));
}
}
But I am getting mockito wanted but not invoked, Actually there were zero interactions with this mock at verify call.
can anyone suggest some solutions.
You need to inject mock inside the class you're testing. At the moment you're interacting with the real object, not with the mock one. You can fix the code in a following way:
void testAbc(){
myClass.myObj = myInteface;
myClass.abc();
verify(myInterface).myMethodToBeVerified(new String("a"), new String("b"));
}
although it would be a wiser choice to extract all initialization code into #Before
#Before
void setUp(){
myClass = new myClass();
myClass.myObj = myInteface;
}
#Test
void testAbc(){
myClass.abc();
verify(myInterface).myMethodToBeVerified(new String("a"), new String("b"));
}
Your class MyClass creates a new MyClassToBeTested, instead of using your mock. My article on the Mockito wiki describes two ways of dealing with this.
#Jk1's answer is fine, but Mockito also allows for more succinct injection using annotations:
#InjectMocks MyClass myClass; //#InjectMocks automatically instantiates too
#Mock MyInterface myInterface
But regardless of which method you use, the annotations are not being processed (not even your #Mock) unless you somehow call the static MockitoAnnotation.initMocks() or annotate the class with #RunWith(MockitoJUnitRunner.class).
#jk1 answer is perfect, since #igor Ganapolsky asked, why can't we use Mockito.mock here? i post this answer.
For that we have provide one setter method for myobj and set the myobj value with mocked object.
class MyClass {
MyInterface myObj;
public void abc() {
myObj.myMethodToBeVerified (new String("a"), new String("b"));
}
public void setMyObj(MyInterface obj)
{
this.myObj=obj;
}
}
In our Test class, we have to write below code
class MyClassTest {
MyClass myClass = new MyClass();
#Mock
MyInterface myInterface;
#test
testAbc() {
myclass.setMyObj(myInterface); //it is good to have in #before method
myClass.abc();
verify(myInterface).myMethodToBeVerified(new String("a"), new String("b"));
}
}
This exception can also be thrown if say, you expect thisMethod() to execute, but it didn't. It didn't because it's inside a condition that was not met.
For example, if you have some unit test that says verify thisMethod() is executed, but in fact, it was not because varX and varY are not equal.
//method expected to be called.
if( varX == varY){
thisMethod();
}
//test
Mockito.verify(foo).thisMethod();

Mockito How to mock only the call of a method of the superclass

I'm using Mockito in some tests.
I have the following classes:
class BaseService {
public void save() {...}
}
public Childservice extends BaseService {
public void save(){
//some code
super.save();
}
}
I want to mock only the second call (super.save) of ChildService. The first call must call the real method. Is there a way to do that?
If you really don't have a choice for refactoring you can mock/stub everything in the super method call e.g.
class BaseService {
public void validate(){
fail(" I must not be called");
}
public void save(){
//Save method of super will still be called.
validate();
}
}
class ChildService extends BaseService{
public void load(){}
public void save(){
super.save();
load();
}
}
#Test
public void testSave() {
ChildService classToTest = Mockito.spy(new ChildService());
// Prevent/stub logic in super.save()
Mockito.doNothing().when((BaseService)classToTest).validate();
// When
classToTest.save();
// Then
verify(classToTest).load();
}
No, Mockito does not support this.
This might not be the answer you're looking for, but what you're seeing is a symptom of not applying the design principle:
Favor composition over inheritance
If you extract a strategy instead of extending a super class the problem is gone.
If however you are not allowed to change the code, but you must test it anyway, and in this awkward way, there is still hope. With some AOP tools (for example AspectJ) you can weave code into the super class method and avoid its execution entirely (yuck). This doesn't work if you're using proxies, you have to use bytecode modification (either load time weaving or compile time weaving). There are be mocking frameworks that support this type of trick as well, like PowerMock and PowerMockito.
I suggest you go for the refactoring, but if that is not an option you're in for some serious hacking fun.
Consider refactoring the code from ChildService.save() method to different method and test that new method instead of testing ChildService.save(), this way you will avoid unnecessary call to super method.
Example:
class BaseService {
public void save() {...}
}
public Childservice extends BaseService {
public void save(){
newMethod();
super.save();
}
public void newMethod(){
//some codes
}
}
I found a way to suppress the superclass method using PowerMockito. 3 simple steps need for this
Use PowerMockito.suppress method and MemberMatcher.methodsDeclaredIn method to supress parent class method
Second add Parent class in #PrepareForTest
Run your test class with PowerMock ie add #RunWith(PowerMockRunner.class) above your test class.
#RunWith(PowerMockRunner.class)
#PrepareForTest({BaseService.class})
public class TestChildService(){
#Spy
private ChildService testChildServiceObj = Mockito.spy(new ChildService());
#Test
public void testSave(){
PowerMockito.suppress(MemberMatcher.methodsDeclaredIn(BaseService.class));
//your further test code
testChildServiceObj.save();
}
}
Note: This will work only when the superclass method does not return anything.
Maybe the easiest option if inheritance makes sense is to create a new method (package private??) to call the super (lets call it superFindall), spy the real instance and then mock the superFindAll() method in the way you wanted to mock the parent class one. It's not the perfect solution in terms of coverage and visibility but it should do the job and it's easy to apply.
public Childservice extends BaseService {
public void save(){
//some code
superSave();
}
void superSave(){
super.save();
}
}
create a package protected (assumes test class in same package) method in the sub class that calls the super class method and then call that method in your overridden sub class method. you can then set expectations on this method in your test through the use of the spy pattern. not pretty but certainly better than having to deal with all the expectation setting for the super method in your test
Even if i totally agree with iwein response (
favor composition over inheritance
), i admit there are some times inheritance seems just natural, and i don't feel breaking or refactor it just for the sake of a unit test.
So, my suggestion :
/**
* BaseService is now an asbtract class encapsulating
* some common logic callable by child implementations
*/
abstract class BaseService {
protected void commonSave() {
// Put your common work here
}
abstract void save();
}
public ChildService extends BaseService {
public void save() {
// Put your child specific work here
// ...
this.commonSave();
}
}
And then, in the unit test :
ChildService childSrv = Mockito.mock(ChildService.class, Mockito.CALLS_REAL_METHODS);
Mockito.doAnswer(new Answer<Void>() {
#Override
public Boolean answer(InvocationOnMock invocation)
throws Throwable {
// Put your mocked behavior of BaseService.commonSave() here
return null;
}
}).when(childSrv).commonSave();
childSrv.save();
Mockito.verify(childSrv, Mockito.times(1)).commonSave();
// Put any other assertions to check child specific work is done
You can do this with PowerMockito and replace behavior only of the parent class method with continuing testing the child's class method. Even when the method is returning some value, lets say a string, you can do something like this:
#RunWith(PowerMockRunner.class)
#PrepareForTest({ BaseService.class })
public class TestChildService() {
private BasicService basicServiceObj;
private ChildService testee;
#Before
public void init() throws Exception {
testee = new ChildService();
basicServiceObj = PowerMockito.spy(new BaseService());
PowerMockito.doReturn("Result").when(basicServiceObj, "save", ... optionalArgs);
}
#Test
public void testSave(){
testee.save();
}
}
If you are returning nothing (void) then instead of doReturn you can use doNothing. Add some optionalArgs if the method have some arguments, if not, then skip that part.
The reason is your base class is not public-ed, then Mockito cannot intercept it due to visibility, if you change base class as public, or #Override in sub class (as public), then Mockito can mock it correctly.
public class BaseService{
public boolean foo(){
return true;
}
}
public ChildService extends BaseService{
}
#Test
#Mock ChildService childService;
public void testSave() {
Mockito.when(childService.foo()).thenReturn(false);
// When
assertFalse(childService.foo());
}
There is simple approach that works for most of cases. You can spy your object and stub the method you want to mock.
Here is an example:
MyClass myObjectSpy = Mockito.spy(myObject);
org.mockito.Mockito.doReturn("yourReturnValue").when(mySpyObject).methodToMock(any()..);
So, when you test your object, you can use myObjectSpy and when methodToMock is called, it will overwrite the normal behavior by a mock method.
This code for a method with return. In case you have a void method you can use doNothing instead.

#BeforeClass and inheritance - order of execution

I have an abstract base class, which I use as a base for my unit tests (TestNG 5.10). In this class, I initialize the whole environment for my tests, setting up database mappings, etc. This abstract class has a method with a #BeforeClass annotation which does the initialization.
Next, I extend that class with specific classes in which I have #Test methods and also #BeforeClass methods. These methods do class-specific initialization of the environment (e.g. put some records into the database).
How I can enforce a specific order of the #BeforeClass annotated methods? I need the ones from the abstract base class to be executed before the ones of the extending class.
Example:
abstract class A {
#BeforeClass
doInitialization() {...}
}
class B extends A {
#BeforeClass
doSpecificInitialization() {...}
#Test
doTests() {...}
}
Expected order:
A.doInitialization
B.doSpecificInitialization
B.doTests
Actual order:
B.doSpecificInitialization // <- crashes, as the base init is missing
(A.doInitialization // <---not executed
B.doTests) // <-/
edit: Answer below is for JUnit, but I will leave it here anyway, because it could be helpful.
According to the JUnit api: "The #BeforeClass methods of superclasses will be run before those the current class."
I tested this, and it seems to work for me.
However, as #Odys mentions below, for JUnit you need to have the two methods named differently though as doing otherwise will result in only the subclass method being run because the parent will be shadowed.
Don't put the #BeforeClass on the abstract class. Call it from each subclass.
abstract class A {
void doInitialization() {}
}
class B extends A {
#BeforeClass
void doSpecificInitialization() {
super.doInitialization();
}
#Test
void doTests() {}
}
Seems like TestNG has #BeforeClass(dependsOnMethods={"doInitialization"}) - give it a try.
I added public to the abstract class and TestNG (6.0.1) executed the doInitialization() before doTests. TestNG does not execute doInitialization() if I remove public from class A.
public abstract class A {
#BeforeClass
doInitialization() {...}
}
class B extends A {
#Test
doTests() {...}
}
I just tried your example with 5.11 and I get the #BeforeClass of the base class invoked first.
Can you post your testng.xml file? Maybe you are specifying both A and B there, while only B is necessary.
Feel free to follow up on the testng-users mailing-list and we can take a closer look at your problem.
--
Cedric
I've just gone through this and found one more way to achieve this. Just use alwaysRun on #BeforeClass or #BeforeMethod in the abstract class, works as you would expect.
public class AbstractTestClass {
#BeforeClass(alwaysRun = true)
public void generalBeforeClass() {
// do stuff
specificBeforeClass();
}
}
For JUnit:
As #fortega has mentioned:
According to the JUnit api: "The #BeforeClass methods of superclasses will be run before those the current class."
But be careful not to name both methods with the same name. Since in this case the parent method will be hidden by child parent. Source.
When I run from: JUnitCore.runClasses(TestClass.class);
It will execute the parent properly, before the child (You do not need super.SetUpBeforeClass();)
If you run it from Eclipse:
For some reason it fails to run the base class.
The work around:
Call the base class explicitely: (BaseTest.setUpBeforeClass();)
You may want to have a flag in the base class in case you run it from an application, to determine if it is already setup or not. So it only runs once if you run it via both possible methods (such as from eclipse for personal testing, and through ANT for a build release).
This appears to be a bug with Eclipse, or at least unexpected results..
How about having your #BeforeClass method call an empty specificBeforeClass() method that may or may not be overwritten by sub classes like so:
public class AbstractTestClass {
#BeforeClass
public void generalBeforeClass() {
// do stuff
specificBeforeClass();
}
protected void specificBeforeClass() {}
}
public class SpecificTest {
#Override
protected void specificBeforeClass() {
// Do specific stuff
}
// Tests
}
dependsOnMethod can be used.
e.g. in case of Spring (AbstractTestNGSpringContextTests)
#BeforeClass(alwaysRun = true, dependsOnMethods = "springTestContextPrepareTestInstance")
Check your import statement.
It should be
import org.testng.annotations.BeforeClass;
not
import org.junit.BeforeClass;
This works for me --
abstract class A {
#BeforeClass
doInitialization() {...}
}
class B extends A {
#Override
#BeforeClass
doInitialization() {
//do class specific init
}
#Test
doTests() {...}
}
Why don't you try to create an abstract method doSpecialInit() in your super class, called from your BeforeClass annotated method in superclass.
So developpers inheriting your class is forced to implement this method.
There is another easy solution here.
My particular situation is that I need to inject mock services from "BeforeClass" in the subclass before "BeforeClass" in the superclass is executed.
To do this - simply use a #ClassRule in the subclass.
For example:
#ClassRule
public static ExternalResource mocksInjector = new ExternalResource() {
#Override
protected void before() {
// inject my mock services here
// Note: this is executed before the parent class #BeforeClass
}
};
I hope this helps. This can effectively execute static setup in "reverse" order.
I've faced a similar issue today, the only difference was a Base class was not abstract
Here's my case
public class A {
#BeforeClass
private void doInitialization() {...}
}
public class B extends A {
#BeforeClass
private void doSpecificInitialization() {...}
#Test
public void doTests() {...}
}
It occurred that a #BeforeClass method from class A was never executed.
A.doInitialization() -> THIS WAS NEVER EXECUTED silently
B.doSpecificInitialization()
B.doTests()
Playing with privacy modifiers I found that TestNG will not execute a #BeforeClass annotated method from inherited class if a method is not visible from a class-inheritor
So this will work:
public class A {
#BeforeClass
private void doInitialization() {...}
}
public class B extends A {
#BeforeClass
//Here a privacy modifier matters -> please make sure your method is public or protected so it will be visible for ancestors
protected void doSpecificInitialization() {...}
#Test
public void doTests() {...}
}
As a result following happens:
A.doInitialization()
B.doSpecificInitialization()
B.doTests()
In my case (JUnit) I have the same methods called setup() in the base class and the derived class. In this case only the derived class's method is called, and I have it call the base class method.
A better and cleaner way to achieve this using inheritance may be as following -
abstract class A {
#BeforeClass
void doInitialization() {}
}
class B extends A {
#Override
#BeforeClass
void doInitialization() {
super.doInitialization();
}
#Test
void doTests() {}
}

Categories

Resources