Junit, java : Mocking a method -



Junit, java : Mocking a method -

i have created java class (a) calling method class (b). other class (b) calling method 3rd class (c). have mocked few methods b class. i'm trying mock method c class . however, not working. test class below:

class="lang-java prettyprint-override">@runwith(mockitojunitrunner.class) public class testa { private a= new a(); @mock private b b; @before public void setup() throws exception { setinternalstate(a, "b", b); } @test public void testmethoda() throws exception { when(b.methodmock(anystring())).thenreturn(myvalue); when(c.methodmockc(anystring()).thenreturn(myvalue2); result=a.methoda("xyz"); assert.assertequals("anyvalue", result.getvalue()); } }

classes tested below.

public class { public b b=new b(); public string methoda (string value) { string myvalue=b.methodmock(value); string result=b.methodb(myvalue,value) homecoming result; } } public class b { public c c=new c(); public string methodb (string myvalue,string value) { string result=c.methodc(myvalue); homecoming result; } public string methodmock (string value) { homecoming result; } } public class c { public string methodc (string myvalue) { result=methodmockc(myvalue); homecoming result; } public methodmockc(string val){ homecoming value; } }

my method b.methodmock working fine c.methodmockc not working (2nd level mock). appreciate response. in advance.

edit: need mock methodmockc in class c getting called methodb->methodc->mockmethodc via injected object b .

several things:

the code, posted, not compile. in class c, have methodmockc() method. returns value variable variable not defined. result variable used in methodc() not defined.

in class c have field of type named c initialized new c(). means whenever you're creating instance of c code seek initialize field entails creation of sec c instance. instance has c field entail creation of 3rd c instance, in turn entail creation of fourth c instance in turn...; see point? when c object created run infinite loop.

in order utilize mocked b object test creates, have somehow inject a object. setinternalstate() doing? specifically, a.b = b ? if not a object not utilize b mock.

there no need mock c class. if a object using mock b object no longer invokes method of original b class , there no need mock c - invoke methods on mock b , behavior of method specified test (in when(b.??????).thenreturn(????) lines).

java junit mockito

Comments

Popular posts from this blog

java Multi query from Mysql using netbeans -

c# - DotNetZip fails with "stream does not support seek operations" -

c++ - StartServiceCtrlDispatcher don't can access 1063 error -