Reputation: 604
I am new to development environment in Java and want to understand how to write a UT for this 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 but how to mock behavior of ClassA and ClassC ? Basically I want to define behaviour of ClassA i.e., "addParam" and " getClassCObj" . How can I do this ?
I need to test "myMethod" of this "MyClass" Thanks.
Upvotes: 0
Views: 282
Reputation: 2764
Because the ClassA object is instantiated within the method, you're not going to be able to mock it with EasyMock.
If you're happy to not mock the ClassA object, then you can add any expectations needed for the mocked instance of ClassB
and then use a capture
to check that the ClassC
object has been built as expected.
So your test would look something like 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 some expectations for how the mockClassBObj is used within the addParam and 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 about the classC object
}
}
Having said all of that, it is possible to use PowerMock to mock the constructor for the ClassA class (assuming you're allowed to use PowerMock)
See the root documentation for powermock here and the specific docs for the Constructor mocking here
Upvotes: 1