This question arise while trying to write test cases. Foo is a class within the framework library which I dont have source access to.
public class Foo{
public final Object getX(){
...
}
}
my applications will
public class Bar extends Foo{
public int process(){
Object value = getX();
...
}
}
The unit test case is unable to initalize as I can't create a Foo object due to other dependencies. The BarTest throws a null pointer as value is null.
public class BarTest extends TestCase{
public testProcess(){
Bar bar = new Bar();
int result = bar.process();
...
}
}
Is there a way i can use reflection api to set the getX() to non-final? or how should I go about testing?
Seb is correct, and just to ensure that you get an answer to your question, short of doing something in native code (and I am pretty sure that would not work) or modifying the bytecode of the class at runtime, and creating the class that overrides the method at runtime, I cannot see a way to alter the "finalness" of a method. Reflection will not help you here.
If your unit test case can't create Foo due to other dependencies, that might be a sign that you're not making your unit test right in the first place.
Unit tests are meant to test under the same circumstances a production code would run, so I'd suggest recreating the same production environment inside your tests. Otherwise, your tests wouldn't be complete.
As this was one of the top results for "override final method java" in google. I thought I would leave my solution. This class shows a simple solution using the example "Bagel" class and a free to use javassist library:
you could create another method which you could override in your test:
then, you could override doGetX in BarTest.
If the variable returned by
getX()
is notfinal
you can use the technique explained in What’s the best way of unit testing private methods? for changing the value of theprivate
variable throughReflection
.what i did eventually was the above. it is a bit ugly... James solution is definitely much better than this...