lundi 1 avril 2019

Temporarily modifying an object that is injected to multiple classes with Java Guava Injector

I am working on a project that has multiple modules and dependency management is done with Guava injector which I am not very familiar with.

For an unit test, I need to override a method of an injected object temporarily (because I want to simulate its failure when it is called by another object).

I could probably do this by modifying the object so that I can configure it to fail like object.setTemporaryFail(failType). Then I also have to add something like if(failType!=null){failType=null; fail(failType);} within the object's method. Although I tried this and it works, I don't think it is very clean, but I don't know what the best practice is (especially because I am not too familiar with this design pattern).

What appears to be a good option to me is to maybe create a class extending the object and temporarily replace it, therefore the object does not need to have any unit test/failure related code in its implementation (which seemed like a better abstraction to me). Specifically I could do something like this:

class objectThatFails extends object{
   FailType failType;
   public objectThatFails(FailType failType){
     this.failType = failType;
   }

   @Override 
   public methodThatShouldFail(...){
      fail(failType);
   }
}

and within the class that does the unit test I could do:

class paranoidUnitTester {
    @Inject
    object

    @Test
    testSpecificFailure(){
       Object originalObject = object;
       object = new objectThatFails(new FailType(stuff));
       driver.drive(); //calls the object fails and recovers
       //now test is complete so we replace the injected object back
       object = originalObject;
    }
}

But this example does not work, and I am not sure if I am breaking a design rule by trying to use injected variables like global variables and if there are any drawbacks of doing this (during unit testing, so its a controlled, simulated environment).

So my questions are:

  • is there such a concept in guava to achieve this goal (ie. is there a way I temporarily overwrite the mentioned object)
  • is this good practice? (or if not, what is?)

Aucun commentaire:

Enregistrer un commentaire