lundi 28 septembre 2015

How to mock a method of bean inside spring util:list (ref)

here the situation:

i got some beans (called Systems). These beans work with external system to gather data and do more (like analyze them, or store them in database etc.). These systems also got some beans to do the work (the work called before, gather / read, analyze, store, etc).

I got a spring context xml where these beans (systems) are defined like:

<bean id="SomeSystem" class"..."/>

All these systems have the same Interface...let's call it "MommyInterfaceSystem"... And i got also a simple util:list config, like this:

<util:list id="MyAwesomeSystemsList">
  <ref bean="SomeSystem"/>
  <ref bean="AnotherSystem"/>
  ...
</util:list>

As you can see i got some "Systems" like "SomeSystem" and "AnotherSystem" - both implementing "MommyInterfaceSystem"...whatever...

These systems are get called over another Class. Let's call it "GatherInformationFromSystems".

This class has this structure:

public class GatherInformationFormSystems {
  @Resource(name "MyAwesomeSystemsList")
  private final List<MommyInterfaceSystem> informationSystems = new ArrayList<MommyInterfaceSystem>();

  public void execute() {
    ...
    for(MommyInterfaceSystem s : informationSystems) {
      ...
      s.gatherInformation();
      ...
    }
    ...
  }
}

And now i want to test the results of this process! And here we arrive the my problem.

I wrote a simple unit test to execute the process of gathering information. This process works and it is fine. I wrote many test for this process and it works greats but if i want to mock an external system (because i want to predefine the return value) it fails...

If i call the gather bean directly (not over the util:list...it works...but then the other actions like analyze or store won't get called...).

I have to do something like this:

If AnotherSystem of informationSystems is calling the "gatherInformation" method of - it is gonna call another method (let's call it "doCall").

And i want to mock this method. The method doCall.

All should be the same, except this method (doCall). Here i want to return a predefined Object.

Sry for this bad explanation, my english is damn bad...but i hope you will understand my problem :/


here i can list what i tried...

  1. i tried to get the system from the list with reflections and replaced it with a mock...the result is a nullpointer exception because of missing autowired beans...

  2. I autowired the bean directly and tried to mock it:

    Mockito.when(anotherSystem.doCall(Mockito.anyString()).thenReturn(data);
    
    
  3. I tried to create the object with EasyMock.mock...also failed


I didn't try to create a xml context to override the bean definition with own bean, because the system contains many other method which get called...and...yeah...pity...

Aucun commentaire:

Enregistrer un commentaire