如何使用MockitoJUnitRunner模拟unmodifiableableMap

时间:2018-07-17 02:32:34

标签: java junit mocking mockito

Class Test {

 private A a;

 private B b; 

}

Class B{

 private final Map<String, Integer> sampleMap = new HashMap();

 public Map<String, Integer> getSampleMap() {

      return Collections.unmodifiableMap(this.sampleMap);
  }

}

如何模拟不可修改的getSampleMap来模拟测试对象。我需要创建并设置键/值对。

1 个答案:

答案 0 :(得分:0)

您可以将b个协作者(类型为B)注入Test类中。 这样做可以模拟b.getSampleMap()

使用Mockito:

import org.junit.Rule;
import org.mockito.Mock;
import org.mockito.junit.MockitoJUnit;
import org.mockito.junit.MockitoRule;

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

import static org.hamcrest.Matchers.is;
import static org.junit.Assert.assertThat;
import static org.mockito.Mockito.when;

public class StackoverflowTest {

  public static class Test {

    private A a;
    private B b;

    public Test(B b) {
      this.b = b;
    }
  }

  public static class A {}

  public static class B {

    private final Map<String, Integer> sampleMap = new HashMap<>();

    public Map<String, Integer> getSampleMap() {
      return Collections.unmodifiableMap(this.sampleMap);
    }
  }

  @Rule
  public MockitoRule mockitoRule = MockitoJUnit.rule();

  @Mock
  private B b;

  @org.junit.Test
  public void testWithMock() {

    Map<String, Integer> expectedMap = new HashMap<>();
    expectedMap.put("a", 1);
    expectedMap.put("b", 2);
    expectedMap.put("c", 3);

    when(b.getSampleMap()).thenReturn(expectedMap);

    Test underTest = new Test(b);

    assertThat(underTest.b.getSampleMap(), is(expectedMap));
  }
}

请注意,断言(assertThat(underTest.b.getSampleMap(), is(expectedMap)))在实际情况下可能没有用。我把它放在那里只是为了验证我的解决方案。