java - PowerMock - How to call manipulate the parameters of a mocked method -


i'm using powermock/easymock test static method in 1 of parameters stringbuffer appended method in mocked class.

this simplified class demonstrate.

import java.util.date;  public class contentchanger {     public static int change(stringbuffer sb)     {         sb.append( new date() );         return 0;     } } 

and here unit test...

import org.easymock.easymock; import org.junit.test; import org.junit.runner.runwith; import org.powermock.api.easymock.powermock; import org.powermock.core.classloader.annotations.preparefortest; import org.powermock.modules.junit4.powermockrunner;  @runwith(powermockrunner.class) @preparefortest(contentchanger.class) public class contentchangertest {     @test     public void test001()     {     // declare empty stringbuffer     stringbuffer var = new stringbuffer();      // enable static mocking contentchanger class     powermock.mockstatic( contentchanger.class );      // catch call , send test method     easymock.expect(contentchanger.change( var )).anddelegateto( test(var) );      // replay mock classes/methods     powermock.replayall();      // call method mocked     system.out.println( contentchanger.change( var ) + " = " + var );     }       private int test( stringbuffer sb )     {         sb.append( "mocked" );         return 1;     } } 

what expect happen test method called , stringbuffer output..

1 = mocked

but happening stringbuffer var updated before mocked method called.

i.e. following...

java.lang.assertionerror:    unexpected method call contentchanger.change(mocked):     contentchanger.change(mocked): expected: 1, actual: 2 

is there way invoke class/method, change contents of parameter when called instead of pre-replay.

the problem calling test(var). anddelegateto expects object of same class/interface mock. see http://easymock.org/user-guide.html#verification-creating.

since on static method, not possible. best use ianswer instead. here working code:

        easymock.expect(contentchanger.change( var )).andanswer(new ianswer<integer>() {         @override         public integer answer() throws throwable {             stringbuffer sb = (stringbuffer) easymock.getcurrentarguments()[0];             sb.append( "mocked" );             return 1;         }     }) 

Comments

Popular posts from this blog

android - Gradle sync Error:Configuration with name 'default' not found -

java - Andrioid studio start fail: Fatal error initializing 'null' -

html - jQuery UI Sortable - Remove placeholder after item is dropped -