vendredi 17 septembre 2021

Is there a way to get an object's private method to do nothing when called?

I'm writing an integration test in Java using JUnit, Mockito, and ReflectionTestUtils. I have the following situation:

Source code that I want to test:

class AClassINeed extends SomeClass{


  public method_I_need_to_call(){

    //some code
    method_that_fails();
    // lots of other calls

  }

  private boolean method_that_fails(){
    // Instantiate a new local object of external dependency
    // Call a method from this new object ==> AKA FAILURE
  }
}

Inside my test method: I need to create a realObject here so that all the real code gets exercises. Except for the method that will fail. I'm currently trying like this:

AClassINeed realObject = new AClassINeed(Lots.class, Of.class, Parameters.class);
AClassINeed spyObject = Mockito.spy(realObject);
Method spyObjectPrivateMethod = spyObject.getClass().getDeclaredMethod("method_that_fails");
spyObjectPrivateMethod.setAccessible(true);
when(spyObjectPrivateMethod).thenReturn(true); // <== Syntax error "Cannot resolve method thenReturn(boolean)"

How can I achieve this? I cannot create a mock object of AClassINeed because I want execute all methods normally except the one that fails.

I also tried with ReflectionTestUtils like this:

Method failingMethod = realObject.getClass().getDeclaredMethod("method_that_fails", String.class, String.class);
failingMethod.setAccessible(true);
ReflectionTestUtils.setField(realObject, "method_that_fails", failingMethod); // <== Wrong! This cannot be done for methods

At this point, I'm stumped.

Is there a way for me to get that failing method to do nothing without mocking out the entire class?





Aucun commentaire:

Enregistrer un commentaire