如何在不使用@injectmocks的情况下注入模拟



我有以下类

public class One {
    private Map<String, String> nodes = new HashMap<String, String>();
    public void addNode(String node, String nodefield){
        this.nodes.put(node, nodefield);
    }
}

我想编写一个测试类来测试 addNode 方法,并具有以下内容:

@RunWith(MockitoJUnitRunner.class)
public class OneTest {
    @InjectMocks
    private One one = new One();
    @Mock
    Map<String, String> nodes;
    @Test
    public void testAddNode(){
        one.addNode("mockNode", "mockNodeField");
        Mockito.verify(nodes).put("mockNode","mockNodeField");
    }
}

哪个有效。但我想知道是否有办法在不使用如下所示@InjectMocks的情况下做到这一点

public class OneTest {
    private One one;
    @Test
    public void testAddNode(){
        Map<String, String> nodes = Mockito.mock(Map.class);
        one = Mockito.injectmocks(One.class, nodes); // or whatever equivalent methods are
        one.addNode("mockNode", "mockNodeField");
        Mockito.verify(nodes).put("mockNode","mockNodeField");
    }
}

通过将映射作为依赖项注入来更改类怎么样?这使得测试更容易,并为您提供了能够使用 Map 接口实现的额外好处,例如:

  public class One {
    private Map<String, String> nodes;
    public One(Map<String, String> nodes) {
        this.nodes = nodes;
    }
    public void addNode(String node, String nodefield){
        this.nodes.put(node, nodefield);
    }
}

然后测试:

Map mockMap = Mockito.mock(Map.class);
One one = new One(mockMap);
one.addNode("mockNode", "mockNodeField");
Mockito.verify(mockMap).put("mockNode","mockNodeField");
好的,

我通过使用PowerMockito而不是普通的Mockito来解决这个问题。

public class OneTest {
    private One one;
    @Test
    public void testAddNode(){
        HashMap nodes = PowerMockito.mock(HashMap.class);
        PowerMockito.whenNew(HashMap.class).withNoArguments().thenReturn(nodes);

        One one = new One(); 
        one.addNode("mockNode", "mockNodeField");
        Mockito.verify(nodes).put("mockNode","mockNodeField");
    }
}

但是,我真的不知道PowerMockito做了什么,而Mockito并没有这样做来使其工作。

相关内容

  • 没有找到相关文章

最新更新