Karl
Karl

Reputation: 223

Comparing two TreeMaps with JUnit

Trying to test that two TreeMaps are the same with the following code:

public class StreamTest {

  private Stream stream;
  private Map<String, AtomicInteger> map = new HashMap<>();

  @Before
  public void setup() {
    stream = new Stream();
    map.put("this", new AtomicInteger(1));
    map.put("is", new AtomicInteger(1));
    map.put("an", new AtomicInteger(1));
    map.put("just", new AtomicInteger(1));
    map.put("example", new AtomicInteger(1));
    map.put("file", new AtomicInteger(1));
    map.put("for", new AtomicInteger(1));
    map.get("this").incrementAndGet();
    map.put("project", new AtomicInteger(1));
  }

  @Test
  public void lineToWordsToMapTest() {
    stream.getLines("testSampleFile");
    Map<String, AtomicInteger> sortedmap = new TreeMap<>(stream.getMap());
    Map<String, AtomicInteger> treemap = new TreeMap<>(map);  // Maps must be sorted in order to pass test
    Assert.assertEquals(treemap, sortedmap);
  }

}

And this is the puzzling error message:

java.lang.AssertionError: expected: java.util.TreeMap<{an=1, example=1, file=1, for=1, is=1, just=1, project=1, this=2}> but was: java.util.TreeMap<{an=1, example=1, file=1, for=1, is=1, just=1, project=1, this=2}>
Expected :java.util.TreeMap<{an=1, example=1, file=1, for=1, is=1, just=1, project=1, this=2}> 
Actual   :java.util.TreeMap<{an=1, example=1, file=1, for=1, is=1, just=1, project=1, this=2}>

So the objects look like they are exactly the same using JUnit 4.12. Any insight would be appreciated.

Upvotes: 2

Views: 844

Answers (2)

Med Elgarnaoui
Med Elgarnaoui

Reputation: 1667

You have get() method for it

Gets the current value.

Returns: the current value

What AtomicInteger::get guarantees is that when you call it, you will get the latest value available at the time of the call. A guarantee which you would not have with a plain int for example.

Upvotes: 1

Karol Dowbecki
Karol Dowbecki

Reputation: 44952

That's because AtomicInteger doesn't override equals() and can't be successfully compared with other instance of AtomicInteger of the same value. You either need to change your map value type or write your own assertion for AtomicInteger.

To simplify:

Assert.assertEquals(new AtomicInteger(1), new AtomicInteger(1));

Results in:

java.lang.AssertionError: expected: java.util.concurrent.atomic.AtomicInteger<1> but was: java.util.concurrent.atomic.AtomicInteger<1>
Expected :java.util.concurrent.atomic.AtomicInteger<1> 
Actual   :java.util.concurrent.atomic.AtomicInteger<1>

Upvotes: 2

Related Questions