jmockit / jmockit1

Advanced Java library for integration testing, mocking, faking, and code coverage
Other
461 stars 239 forks source link

NPE running jmockit outside junit #106

Closed morsmodre closed 9 years ago

morsmodre commented 9 years ago

In order to end-to-end test some things I have a simple class I want to mock:

public final class ClassToMock {
    private enum Enum {
        HIGH, MEDIUM, LOW
    }

    public static String toMock(String param) {
        // TODO
        return Enum.LOW.name();
    }
}

In order to mock the method I have this in another class:

MockUp mock = new MockUp<ClassToMock>() {
    @Mock
    public String toMock(String param) {
        return "lol";
    }
};

Now, when I call that toMock in that class (notice, this is in runtime not in testes):

Customer.risk("");

I get this exception:

java.lang.NullPointerException: null at mockit.internal.state.MockClasses.getMock(MockClasses.java:103) at mockit.internal.state.TestRun.getMock(TestRun.java:127) at mockit.internal.state.TestRun.updateMockState(TestRun.java:112)

What happens is that in this line:

INVOKED_INSTANCE_FIELD.set(mockUpInstances.initialMockUp, invokedInstance);

The mockUpInstances is null. Since the map mockupClassesToMockupInstances is empty.

Any idea what is going on here?

rliesenfeld commented 9 years ago

I will need more information to understand this. Can you show a minimal example Java class with a "main" method which reproduces the failure?

morsmodre commented 9 years ago

I'll try to do it, but I have a feeling that it has something to do with classloaders. My application has a classloader for each service and it's that service that is calling (and mocking) the method. Does jmockit has some side-behaviour with diferent classloaders?

morsmodre commented 9 years ago

Can reproduce this with a smaller project.

What happens is that the TestRun#updateMockState has the mockedInstance parameter as null when its invoked through the bytecode.

The comment says the following:

    // Methods to be called only from generated bytecode or from the MockingBridge 

Any idea what can be wrong? What is the mockedInstance object?

Thanks!