Search code examples
kotlinnullpointerexceptioneasymock

How to solve EasyMock anyString() NullPointerException in Kotlin?


I am using EasyMock with Kotlin. It works well but I bumped into a case when I need to mock 3rd party library call and I don't objectively need/have to verify the first param, so I want to use this construction:

EasyMock.expect(bucket.putObject(EasyMock.anyString(), message)).andReturn(PutObjectResult())

I am getting null pointer exception.

java.lang.NullPointerException: anyString() must not be null

The reason why, underneath EasyMock has this implementation:

public static String anyString() {
    return (String)anyObject();
}

public static <T> T anyObject(Class<T> clazz) {
    reportMatcher(Any.ANY);
    return null;
}

I took a look at possible workarounds as in Mockito but nothing of this worked for me.

Is there a way to overcome this inconvenience with EasyMock and not getting NullPointer exception?


Solution

  • I am not a Kotlin expert. My first thought was that bucket.putObject isn't actually mocked. But it might be because anyObject() just returns null and the null validation in Kotlin causes that.

    You could create your own matcher.

    public static String anyString() {
        EasyMock.reportMatcher(Any.ANY);
        return "";
    }
    

    And see if it works.