2014-09-24 10 views
1

POJO에게 인 키에서 맵의 값을 얻는 방법나는 다음과 같은 기능을 가지고

Map<MyClass, String> someFunction() { 
    Map<MyClass, String> result = new HashMap<>(); 
    return result.put(new MyClass("someString"), "someOtherString")); 
} 
MyClass에의 구현은 다음과 같습니다

: 내 테스트 I에서

public class MyClass{ 

    String string; 

    public MyClass(String string) { 
     this.string = string; 
    } 

    public void setString(String string) { 
     this.string = string; 
    } 

    @Override 
    public int hashCode() { 
     final int prime = 31; 
     int result = 1; 
     result = prime * result + ((string== null) ? 0 : string.hashCode()); 
     return result; 
    } 

    @Override 
    public boolean equals(Object obj) { 
     if (this == obj) { 
      return true; 
     } 
     if (obj == null) { 
      return false; 
     } 
     if (getClass() != obj.getClass()) { 
      return false; 
     } 
     MyClass other = (MyClass) obj; 
     if (string== null) { 
      if (other.string!= null) { 
       return false; 
      } 
     } else if (!string.equals(other.string)) { 
      return false; 
     } 
     return true; 
    } 

} 

다음을 수행합니다.

@Test 
public void test() { 
    Map<MyClass, String> outcome = classUnderTest.someFunction(); 

    assertThat(outcome.get(new MyClass("someString")), is("someOtherString")); 
} 

그러나이 테스트는 실패합니다. 왜냐하면 actual가 null이기 때문입니다. 나는 다음과 같은 시도 할 경우 :

assertThat(outcome.keySet(), hasItem(MY_CLASS)); 

이 이러한 다른 intantiations 것을, 말해, 실패합니다. 나는 심지어 내 테스트를 디버그하려했지만 equals 메소드에 도달하지 못했다. 여기서 무슨 일이 일어 났는지 말해 줄 수 있니?) (

공공 V 넣어 (K 키, V 값)

Associates the specified value with the specified key in this map. If the map previously contained a mapping for the key, the old value is replaced. 

Specified by: 
    put in interface Map<K,V> 
Overrides: 
    put in class AbstractMap<K,V> 
Parameters: 
    key - key with which the specified value is to be associated 
    value - value to be associated with the specified key 
Returns: 
    the previous value associated with key, or null if there was no mapping for key. (A null return can also indicate that the map previously associated null with key.) 

넣어 반환 : 함수에서

+0

junit의 어떤 버전을 사용하고 있습니까? – Eben

+0

현재 버전 4.11을 사용 중입니다. – Chris311

답변

0

당신의 메소드가 objecT를 수정하지 않았습니까? 내 생각에 이 someFunction으로 바뀌 었습니다. MyClass입니다. 그 결과 MyClass의 객체는 다른 hashCode를 반환합니다. 그런

HashMap 작품 :

넣어 :

  • 컴퓨팅 키의 hashCode. 키의

    • 컴퓨팅 hashCode : 그 해시 코드

    GET에서 저장 값입니다. 그 hashCode로 값을 검색하십시오. 값이 있으면 equals으로 전화하십시오.

그래서 키로 변경 가능한 값을 사용하지 마십시오! 그렇지 않으면, 당신은 그것을

녹색
import static org.hamcrest.Matchers.is; 
import static org.junit.Assert.assertThat; 

import java.util.HashMap; 
import java.util.Map; 

import org.junit.Test; 

public class SomeTest { 

    Map<MyClass, String> someFunction() { 
     Map<MyClass, String> result = new HashMap<>(); 
     result.put(new MyClass("someString"), "someOtherString"); 
     return result; 
    } 

    @Test 
    public void test() { 
     Map<MyClass, String> outcome = someFunction(); 

     assertThat(outcome.get(new MyClass("someString")), is("someOtherString")); 
    } 

    public static class MyClass { 

     String string; 

     public MyClass(String string) { 
      this.string = string; 
     } 

     public void setString(String string) { 
      this.string = string; 
     } 

     @Override 
     public int hashCode() { 
      final int prime = 31; 
      int result = 1; 
      result = prime * result + ((string == null) ? 0 : string.hashCode()); 
      return result; 
     } 

     @Override 
     public boolean equals(Object obj) { 
      if (this == obj) { 
       return true; 
      } 
      if (obj == null) { 
       return false; 
      } 
      if (getClass() != obj.getClass()) { 
       return false; 
      } 
      MyClass other = (MyClass) obj; 
      if (string == null) { 
       if (other.string != null) { 
        return false; 
       } 
      } else if (!string.equals(other.string)) { 
       return false; 
      } 
      return true; 
     } 

    } 
} 

일해야하지만, 당신의 데이터가 손실 (또는 어려운 해결 할 수 있도록)

그냥이 테스트를 실행하려고 할 수 있습니다 그것은 Map에 추가 된 후 MyClass 객체를 수정하는 경우, 테스트가 빨간색이되었습니다 :

Map<MyClass, String> someFunction() { 
    Map<MyClass, String> result = new HashMap<>(); 
    MyClass key = new MyClass("someOldString"); 
    result.put(key, "someOtherString"); 
    key.setString("someString"); 
    return result; 
} 
+0

사실 그 질문의 출처를 모릅니다. 너무 길어서 더 이상 상황을 알지조차 모릅니다.나는 당신의 대답이 집에 타는 것 같아서 해결책으로 표시합니다. – Chris311

0

당신의 HashMap를위한 JavaDoc에서 null

을 반환하는 그곳에 있었는데, 방금 쓴 게 아니야.

관련 문제