简体   繁体   中英

how to inject mock without using @injectmocks

I have the following class

public class One {
    private Map<String, String> nodes = new HashMap<String, String>();

    public void addNode(String node, String nodefield){
        this.nodes.put(node, nodefield);
    }
}

I want to write a test class to test the addNode method and have the following:

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

which works. But I was wondering if there is a way to do it without using @InjectMocks like the following

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

How about change the class by injecting the map as a dependency? This makes it easier to test and gives you the added benefit of being able to use an implementation of the Map interface, for example:

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

    }
}

Then to test:

Map mockMap = Mockito.mock(Map.class);

One one = new One(mockMap);

one.addNode("mockNode", "mockNodeField");

Mockito.verify(mockMap).put("mockNode","mockNodeField");

Okay I figured it out by using PowerMockito instead of normal 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");
    }
}

However, I don't really know what PowerMockito does that Mockito doesn't do to make it work though.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM