EasyMock在创建构造函数和抛出NullPointerException时调用哈希码

时间:2013-05-05 15:50:47

标签: junit nullpointerexception easymock

我不明白为什么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)

0 个答案:

没有答案