3

How to write junit for the statement

if (!messageMap.isEmpty())

where messageMap is a TreeMap. I wrote as follows,

PowerMockito.when(!messageMap.isEmpty()).thenReturn(true);

But this code not working.

Nidheesh
  • 47
  • 1
  • 2
  • 10

3 Answers3

1

It is not clear what you are asking for.

When you just want to ensure that your production call makes that call to isEmpty() and then the ideal way of testing is to simply pass empty and non-empty maps to your code under test.

Meaning; you do something like:

@Test
public void testWithEmptyMap() {
  UnderTest underTest = new UnderTest(Collections.emptyMap());
  assertThat(underTest.foo(), is(whatever));

@Test
public void testWithFilledMap() {
  UnderTest underTest = new UnderTest(Collections.singletonMap(key, value));
  assertThat(underTest.foo(), is(somethingElse));

In other words: the best way of testing goes without mocking. You give your code under test different input; and you assert that you get the expected results for the different input values.

But of course, sometimes you have to control how mocked objects passed to your code under test behave; and in that case, yes, you could actually do create a messageMap mock and configure it like:

Mockito.when(messageMap.isEmpty()).thenReturn(false);

But: that would be bad practice. You only mock objects that you can't control easily. A map is super-easy to control; simply by pushing some content into it (or leaving it empty). So instead of passing a mocked map configured to be empty or contain a value ... pass a real map; either empty or containing some values!

GhostCat
  • 137,827
  • 25
  • 176
  • 248
0

Usually you shouldn't mock any util classes(List, Map or Set).You can write test case by following below two approaches

Approach 1: If you want messageMap.isEmpty() should return true then create empty tree object as below.

Map<K, V> messageMap = new TreeMap<>();

Approach 2: If you want messageMap.isEmpty() should return false then create tree object as below.

    Map<K, V> messageMap = new TreeMap<>();
     messageMap.put(k1,v1);
     messageMap.put(k2,v2);

and just pass messageMap object to actual class method, it should work fine.

Hope this is useful.

Praveen Kumar Mekala
  • 628
  • 1
  • 10
  • 26
-1

Are you trying to mock the call or to make an assertion?

In case of mock you can write:

Mockito.when(messageMap.isEmpty()).thenReturn(false);

In case of assertion:

Assert.assertTrue(messageMap.isEmpty());
eugene82
  • 8,432
  • 2
  • 22
  • 30