lundi 6 juillet 2015

Using jmockit, how to avoid the impact between two cases?

I have two classes, the first class:

public class FirstClass {
    private static final Logger LOG = Logger.getLogger(FirstClass.class);

    public void action(){
        LOG.info("FirstClass.action.");
    }
}

the second class:

public class SecondClass {
    private static final Logger LOG = Logger.getLogger(SecondClass.class);

    public void action(){
        FirstClass firstClass = new FirstClass();
        firstClass.action();
    }
}

I will write unit test for these two classes, the first class unit test:

public class FirstClassTest {
    @Test
    public void testAction(){
        FirstClass firstClass = new FirstClass();
        firstClass.action();
    }
}

the second class unit test:

public class SecondClassTest {
    @Mocked
    private Logger LOG;

    @Mocked
    private FirstClass firstClass;

    @Test
    public void testAction(){
        SecondClass secondClass = new SecondClass();
        secondClass.action();
    }
}  

About the second class unit test, As the second class depend on the first class, so I mocked the first class, at same time I also mocked Logger class.

I add a suite class to run these two classes:

@RunWith(Suite.class)
@Suite.SuiteClasses({SecondClassTest.class ,FirstClassTest.class})
public class TestAll {
}

When I run this suite class, it throw the follow exception:

java.lang.NullPointerException
at org.apache.log4j.Category.info(Category.java:663)
at steve.test.jmockit.issues.mocklog4j.FirstClass.action(FirstClass.java:12)
at steve.test.jmockit.issues.mocklog4j.FirstClassTest.testAction(FirstClassTest.java:12)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at com.intellij.junit4.JUnit4IdeaTestRunner.startRunnerWithArgs(JUnit4IdeaTestRunner.java:78)
at com.intellij.rt.execution.junit.JUnitStarter.prepareStreamsAndStart(JUnitStarter.java:212)
at com.intellij.rt.execution.junit.JUnitStarter.main(JUnitStarter.java:68)
at com.intellij.rt.execution.application.AppMain.main(AppMain.java:140)

From this trace log, the LOG of first class has been mocked. but in fact I don't mock Logger in FirstClassTest class.

But when I changed this suite class, firstly run FirstClassTest.class, and then run SecondClassTest.class. all cases are successful.

@RunWith(Suite.class)
@Suite.SuiteClasses({FirstClassTest.class ,SecondClassTest.class})
public class TestAll {
}

How to fix this issue and ensure that there is no effect between the two cases? Thanks!

Aucun commentaire:

Enregistrer un commentaire