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

时间:2017-04-07 21:26:08

标签: java unit-testing testing mocking mockito

我有以下课程

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");
    }
}

2 个答案:

答案 0 :(得分:0)

如何通过将地图注入依赖项来更改类?这使得测试更容易,并且为您提供了使用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");

答案 1 :(得分:0)

好吧,我通过使用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并没有做到让它发挥作用。