mercredi 11 avril 2018

How to mock objects which are used with LazyInitializer?

A team member added some LazyInitializer stuff into some core libraries, now my tests fail because actually I dont know how to mock such objects

    class SomeClass
        public static final LazyInitializer<MyService> SERVICE = new LazyObjectInitializer<>(MyService.class);

        public String someMethod()
        {
            return SERVICE.get().getContent("foo");
        }
    }

Now I want to test the someMethod, but for that I need to somehow mock the service.

 public void testSomeMethod()  {
        MyService service = mock(MyService.class);
        LazyInitializer<MyService> JOB_SVC = new LazyObjectInitializer<>(MyService.class);
        when(JOB_SVC.get()).thenReturn(service);
        when(service.getContent("foo")).thenReturn("bar");

        assertTrue(JOB_SVC.get().getContent().equals("bar"));
    }

Here is the LazyObjectInitializer, the LazyInitializer is from org.apache.commons.lang3.concurrent

public class LazyObjectInitializer<T>
    extends LazyInitializer<T>
{

private final Class<T> serviceInterface;

public LazyObjectInitializer( Class<T> serviceInterface ) {
    super();
    this.serviceInterface = serviceInterface;
}

@Override
protected T initialize() {
    return ObjectConfig.getRegistry().get( serviceInterface );
}
}

Aucun commentaire:

Enregistrer un commentaire