プロパティに値を割り当てる前に EasyMock が hashcode() を自動的に呼び出す理由がわかりません。プロパティの値を設定する代わりに、テストクラスでコンストラクターを作成しているとき、オーバーライドされて NullPointerException をスローする hashcode() を呼び出します。Junittest 用の PowerMock と組み合わせた EasyMock を使用しました
コードは次のようになります。
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)