JUnit Test method that uses other methods in the same object

Hi, I am struggling with a simple problem.

General idea:

class Foo(){
  public boolean method1();
  public String method2();
  public String method3();
  public String shortcut(){
    return (method1() == true) ? method2() : method3();
  }
}

How can I check the quick access method?

I know how to simulate objects and test methods that use another object. Example:

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 the hasGotExternalDevicesAttached () method? This is just an example of a not real scenario. How can I check the drive method? Should I also make fun of the hasGotExternalDevicesAttached function?

Can I mock a class that is being tested?

+5
source share
3 answers

You can create a subclass CarAutoPilotin which you override hasGotExternalDevicesAttached()and run a test with an instance of this subclass.

You can do it inline:

CarAutoPilot cap = new CarAutoPilot() {
    public boolean hasGotExternalDevicesAttached(){
        // return true or false depending on what you want to test
    }
};

unit test CarAutoPilot.

, : -)

+3

. , .

:

  public boolean method1();
  public String method2();
  public String method3();

, , , ( im ), , .

hasGotExternalDevicesAttached(), mocker io, .

, " " . , , , .

+3

Yes, you can using the EasyMock class extension library . In the EasyMock documentation section, find "Partial bullying."

The idea is to make fun of only one (or some) of the object's methods and test methods that depend on the mocked method.

+1
source

All Articles