i have class
class a{ map<string, string> obj; b b; public void method1(str1, str2, str3){ obj = (new map dependent on str1 , str2) string str = b.method2(obj, str3) return str; } how can mock b.method2. mean want test method1 , check correct string returned. purpose want when(b.method2()).thenreturn("mystr").
here complete, working example:
public class b { public string method2(map<string, string> obj, string str3) { // irrelevant our test of return null; } } public class { private map<string, string> obj; private b b; public a(b b) { this.b = b; } /** * replaces internal obj map new map containing str1 key , str2 value, * , calls b.method2() map , str3. * @return value returned b.method2() */ public string method1(string str1, string str2, string str3) { obj = new hashmap<>(); obj.put(str1, str2); string str = b.method2(obj, str3); return str; } public map<string, string> getobj() { return obj; } } public class atest { @test public void method1shouldcallmethod2withcreatedmap() { b mockb = mock(b.class); map<string, string> expectedmap = new hashmap<>(); expectedmap.put("hello", "world"); when(mockb.method2(expectedmap, "!")).thenreturn("ok"); a = new a(mockb); string result = a.method1("hello", "world", "!"); assertequals("ok", result); assertequals(expectedmap, a.getobj()); } // same test, other technique @test public void method1shouldcallmethod2withcreatedmap2() { b mockb = mock(b.class); when(mockb.method2(mockito.<map<string, string>>any(), anystring())).thenreturn("ok"); a = new a(mockb); string result = a.method1("hello", "world", "!"); assertequals("ok", result); map<string, string> expectedmap = new hashmap<>(); expectedmap.put("hello", "world"); assertequals(expectedmap, a.getobj()); verify(mockb).method2(expectedmap, "!"); } }
Comments
Post a Comment