java - how to inject mock without using @injectmocks -
i have following class
public class 1 { private map<string, string> nodes = new hashmap<string, string>(); public void addnode(string node, string nodefield){ this.nodes.put(node, nodefield); } } i want write test class test addnode method , have following:
@runwith(mockitojunitrunner.class) public class onetest { @injectmocks private 1 one = new one(); @mock map<string, string> nodes; @test public void testaddnode(){ one.addnode("mocknode", "mocknodefield"); mockito.verify(nodes).put("mocknode","mocknodefield"); } } which works. wondering if there way without using @injectmocks following
public class onetest { private 1 one; @test public void testaddnode(){ map<string, string> nodes = mockito.mock(map.class); 1 = mockito.injectmocks(one.class, nodes); // or whatever equivalent methods one.addnode("mocknode", "mocknodefield"); mockito.verify(nodes).put("mocknode","mocknodefield"); } }
how change class injecting map dependency? makes easier test , gives added benefit of being able use implementation of map interface, example:
public class 1 { 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 test:
map mockmap = mockito.mock(map.class); 1 one = new one(mockmap); one.addnode("mocknode", "mocknodefield"); mockito.verify(mockmap).put("mocknode","mocknodefield");
Comments
Post a Comment