I do not understand why EasyMock automatically calls hashcode() before assigning values for properties. When I'm creating the constructor in test class, instead of setting the value for properties, it calls hashcode() that is overridden and throwing an NullPointerException. I used EasyMock combined with PowerMock for Junittest
The code looks like as following:
Class Customer{
/**
* Creating a constructor
*/
public Customer(String name, String familyName, B b) throws IllegalArgumentException{
initAttr(name, familyName, b);
}
private void initAttr(String name, String familyName, B b) throws IllegalArgumentException{
if (name == null || familyName == null || b == null)
throw new IllegalArgumentException("Invalid input");
this.name = name;
this.familyName = familyName;
this.b = b;
}
/**
*Test will call this method before setting value for properties
* so now : name and familyName is null-> throw an exception
**/
@Override
public int hashCode() {
// Very simple approach:
// Using Joshua Bloch's recipe:
int result = 17;
result = 37 * result + this.name.hashCode();
result = 37 * result + this.familyName.hashCode();
return result;
}
}
I implement a test class:
@RunWith(PowerMockRunner.class)
@PrepareForTest({Customer.class, Datutil.class})
class TestCustomer{
void setUp{
mockB = createMock(B.class)
}
@Test
public void testConstructor(){
//do replay()...<br/>
a = new Customer("name","faname", mockB);//the error happens here
//do verify()...<br/>
}
}
Thanks very much.
Here is the error log:
java.lang.NullPointerException
at lib.customer.Customer.hashCode(Customer.java:253)
at java.util.HashMap.hash(Unknown Source)
at java.util.HashMap.getEntry(Unknown Source)
at java.util.HashMap.get(Unknown Source)
at org.powermock.core.MockRepository.getInstanceMethodInvocationControl(MockRepository.java:136)
at org.powermock.core.MockGateway.doMethodCall(MockGateway.java:57)
at org.powermock.core.MockGateway.methodCall(MockGateway.java:84)
at lib.customer.Customer.initAttr(Customer.java)
at lib.customer.Customer.<init>(Customer.java:96)
at test.lib.customer.TestCustomer.testConstructor(TestCustomer.java:122)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
at java.lang.reflect.Method.invoke(Unknown Source)
at org.junit.internal.runners.TestMethod.invoke(TestMethod.java:68)
at org.powermock.modules.junit4.internal.impl.PowerMockJUnit44RunnerDelegateImpl$2.runTestMethod(PowerMockJUnit44RunnerDelegateImpl.java:217)
at org.junit.internal.runners.MethodRoadie$2.run(MethodRoadie.java:88)
at org.junit.internal.runners.MethodRoadie.runBeforesThenTestThenAfters(MethodRoadie.java:96)