java - EasyMock: How to test this method -
i new development environment in java , want understand how write ut kind of method in java using easymock.
public class myclass{ public classb classbobj; public int mymethod(someclass someclassobj){ classa obja = new classa(); obja.addparam(classbobj); classc classcobj = obja.getclasscobj(classbobj); return someclassobj.getresult(classcobj); } }
i can create mocks of someclass, classb how mock behavior of classa , classc ? want define behaviour of classa i.e., "addparam" , " getclasscobj" . how can ?
i need test "mymethod" of "myclass" thanks.
because classa object instantiated within method, you're not going able mock easymock.
if you're happy not mock classa object, can add expectations needed mocked instance of classb
, use capture
check classc
object has been built expected.
so test this:
import static org.hamcrest.corematchers.is; import static org.junit.assert.assertthat; import org.easymock.capture; import org.easymock.easymock; import org.junit.before; import org.junit.test; public class myclasstest { private myclass myclass; private someclass mocksomeclassobj; private classb mockclassbobj; @before public void setup() throws exception { this.mocksomeclassobj = easymock.createmock(someclass.class); this.mockclassbobj = easymock.createmock(classb.class); this.myclass = new myclass(); this.myclass.classbobj = this.mockclassbobj; } @test public void thatmethoddoesexpectedthings() { //add expectations how mockclassbobj used within addparam , getclasscobj methods final capture<classc> classccapture = new capture<classc>(); easymock.expect(this.mocksomeclassobj.getresult( easymock.capture(classccapture) ) ).andreturn(9); easymock.replay(this.mockclassbobj, this.mocksomeclassobj); final int result = this.myclass.mymethod(this.mocksomeclassobj); assertthat(result, is(9)); easymock.verify(this.mockclassbobj, this.mocksomeclassobj); final classc classcobject = classccapture.getvalue(); //some assertions classc object } }
having said of that, possible use powermock mock constructor classa class (assuming you're allowed use powermock)
see root documentation powermock here , specific docs constructor mocking here
Comments
Post a Comment