I am having certain classes and their behaviour to test.
class Work {
private static final INSTANCE = new Work();
protected Work() {
}
public Work getInstance() {
return INSTANCE;
}
public void firstWork() throws Exception {
// do something
}
public void secondWork() throws Exception {
// do something
}
public void thirdWork() throws Exception {
// do something
}
public void revertFirstWork() throws Exception {
// do something
}
public void revertSecondWork() throws Exception {
// do something
}
}
class Manager {
public Manager() {
}
public void doWorks() {
Work work = Work.getInstance();
work.firstWork();
try {
work.secondWork();
} catch(Exception e) {
work.revertSecondWork();
}
try {
work.thirdWork();
} catch(Exception e) {
work.revertFirstWork();
work.revertSecondWork();
}
}
}
I have a testing class that uses JUnit to test the reverting methods
class MyTest {
private void setWorkUsingReflection(Work work) {
Field field = Work.class.getDeclaredField("INSTANCE");
field.setAccessible(true);
Field modifiersField = Field.class.getDeclaredField("modifiers");
modifiersField.setAccessible(true);
modifiersField.set(field, field.getModifiers() & ~Modifier.FINAL);
field.set(null, work);
}
@Test
public void testRevertFirstWork() {
class RevertFirstWork extends Work {
RevertFirstWork() {
super();
}
@Override
public void secondWork() throws Exception {
throws new Exception("Known Exception");
}
}
Work work = Work.getInstance();
try {
Manager manager = new Manager();
setWorkUsingReflection(new RevertFirstWork());
manager.doWorks();
} finally {
setWorkUsingReflection(work);
}
}
@Test
public void testRevertFirstAndSecondWork() {
class RevertFirstAndSecondWork extends Work {
RevertFirstWork() {
super();
}
@Override
public void thirdWork() throws Exception {
throws new Exception("Known Exception");
}
}
Work work = Work.getInstance();
try {
Manager manager = new Manager();
setWorkUsingReflection(new RevertFirstAndSecondWork());
manager.doWorks();
} finally {
setWorkUsingReflection(work);
}
}
}
This test cases does not actually work as the instance is not changed to the respective child class via reflection.
On debugging I could not find any relevant findings.
Why the instance is not changed via reflection here ?
Thanks in advance.
Aucun commentaire:
Enregistrer un commentaire