我不明白为什么 EasyMock 在为属性分配值之前会自动调用 hashcode() 。当我在测试类中创建构造函数时,它不是设置属性值,而是调用被覆盖的 hashcode() 并抛出 NullPointerException。我将 EasyMock 与 PowerMock 结合用于 Junittest
代码如下所示:
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;
}
}
我实现了一个测试类:
@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/>
}
}
非常感谢。
这是错误日志:
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)