Hello I am struggling with simple problem.
General idea:
class Foo(){
public boolean method1();
public String method2();
public String method3();
public String shortcut(){
return (method1() == true) ? method2() : method3();
}
}
How should I test shortcut method?
I know how to mock objects and test methods that use other object. Sample:
class Car{
public boolean start(){};
public boolean stop(){};
public boolean drive(int km){};
}
class CarAutoPilot(){
public boolean hasGotExternalDevicesAttached(){
//Hardware specific func and api calls
//check if gps is available
//check if speaker is on
//check if display is on
}
public boolean drive(Car car, int km){
//drive
boolean found = hasGotExternalDevicesAttached();
boolean start = c.start();
boolean drive = c.drive(km);
boolean stop = c.stop();
return (found && start && drive && stop) == true;
}
}
class CarAutoPilotTest(){
@Test
public void shouldDriveTenKm(){
Car carMock = EasyMock.Create(Car.class);
EasyMock.expect(carMock.start()).andReturns(true);
EasyMock.expect(carMock.drive()).andReturns(true);
EasyMock.expect(carMock.stop()).andReturns(true);
EasyMock.reply(carMock);
CarAutoPilot cap = new CarAutoPilot();
boolean result = cap.drive(cap,10);
Assert.assertTrue(result);
EasyMock.verify(carMock);
}
}
But what about hasGotExternalDevicesAttached() method? This is only sample not real scenario. How should I test drive method? Should I also mock hasGotExternalDevicesAttached function?
Can I mock class that is being tested?
You can create a subclass of
CarAutoPilotin which you overridehasGotExternalDevicesAttached(), and run the test with an instance of this subclass.You can do it inline:
This way you can create a valid unit test for the rest of
CarAutoPilot‘s behaviour.You can call this a poor man’s partial mock if you wish 🙂