vendredi 16 septembre 2016

How to mock methods in dynamically loaded jars

I have a class called Price with constructor, which I am dynamically loading via reflection:

public Price(Context context, String pair) {
    this.context = context;
    this.value1 = pair.substring(0, 3);
    this.value2 = pair.substring(3, 6);
    this.dps = context.getService().getm1(value1, value2).getm2();
}

However I want to mock the Context object

and I want

context.getService().getm1(value1, value2).getm2()

to return 5.

Here is what I have tried

//mocking the Context class
Class<?> contextClass = urlClassLoader.loadClass("com.algo.Context");
constructor =contextClass.getConstructor();
Object context = Mockito.mock(contextClass);

//trying to instantiate the Price class
Class<?> priceClass = urlClassLoader.loadClass("com.algo.Price");
constructor = priceClass.getConstructor(beanClass1,String.class);
Mockito.when(context.getService().getm1(value1, value2).getm2().thenReturn(5));
Object price = constructor.newInstance(context,"PRICES");

However I have a red line under

context.getService()

The error says

The method getService() is undefined for the type Object

How can I get around this, my end goal is to create the Price object with the variable

dps

being an int 5, that is why I want to mock the Context object.





Aucun commentaire:

Enregistrer un commentaire