2016-09-16 45 views
0

我有一个叫价与构造类,我动态通过反射加载:如何嘲笑的动态加载的罐子方法

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(); 
} 

但是我想嘲笑上下文对象

,我想

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

返回5

这是我曾尝试

//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(contextClass,String.class); 
Mockito.when(context.getService().getm1(value1, value2).getm2().thenReturn(5)); 
Object price = constructor.newInstance(context,"PRICES"); 

不过我下

context.getService() 

红线错误说

The method getService() is undefined for the type Object 

我怎样才能解决这个搞定了,我的最终目标是与变量建立价格目标

dps 

是一个int 5,这就是为什么我想模拟上下文对象。

+0

上下文是'Object'类型 - 只是施放它。顺便说一句:你在谈论编译器错误 – home

+0

这是一个编译错误,铸造不解决它 – user3809938

+0

为什么你的'上下文'变量的类型'对象',而不是'上下文' – sidgate

回答

0

无法真正理解此问题。如果您使用的是未知类型,则不能在建筑师中输入上下文。

但独立地,一种方法是创建接口来表示预期的上下文结构,然后模拟接口以返回值。 如果它被任何一种方式嘲笑,没有必要在测试中真正加载动态类。

1

对我来说,唯一的办法就是用反射来实现你的整个测试,尤其是在你的情况下,你需要为每个方法调用做同样的事情,因为你不能直接模拟context.getService().getm1(value1, value2).getm2()

假设我有一个类Context如下

public class Context { 

    public int getm1(String value1, String value2) { 
     return -1; 
    } 
} 

一个正常测试的情况将是:

@Test 
public void normal() throws Exception { 
    Context context = Mockito.mock(Context.class); 
    Mockito.when(context.getm1(Mockito.anyString(), Mockito.anyString())).thenReturn(5); 
    Assert.assertEquals(5, context.getm1("foo", "bar")); 
} 

使用反射相同的测试将是:

@Test 
public void reflection() throws Exception { 
    ... // Here I get the classloader 
    // Get the class by reflection 
    Class<?> contextClass = urlClassLoader.loadClass("com.algo.Context"); 
    // Mock the class 
    Object context = Mockito.mock(contextClass); 
    // Get the method by reflection 
    Method method = contextClass.getMethod("getm1", String.class, String.class); 
    // Invoke the method with Mockito.anyString() as parameter 
    // to get the corresponding methodCall object 
    Object methodCall = method.invoke(context, Mockito.anyString(), Mockito.anyString()); 
    // Mock the method call to get what we expect 
    Mockito.when(methodCall).thenReturn(5); 
    // Test the method with some random values by reflection 
    Assert.assertEquals(5, method.invoke(context, "foo", "bar")); 
}