2017-09-01 93 views
0

考虑惩戒一个参数的构造函数如下代码:使用powermockito

@Override 
public void A() { 
    objectA = objectB.B(); 
    objectA.C(someValue); 
     objectC = new constructor(objectA,callback()); 
     //Rest of the code 
    } 

} 
public Callback callback() { 
    return new callback() { 
     @Override 
     public void someMethod(someArgument) { 
      //some Code   
     } 
    }; 
} 

我试图写一个单元测试情况:

  • 通话objectB.B()必须被嘲笑
  • 的致构造函数必须被嘲笑

这就是我所做的使用的Mockito和Powermockito:

@InjectMocks 
ClassBeingTested testObject; 

@Mock 
ClassB objectB; 

@Mock 
ClassC objectC;  

@Before() 
public void setup() { 
    when(objectB.B()).thenReturn(new ObjectA("someValue")); 

    whenNew(objectC.class).withArguments(any(),any()).thenReturn(objectC); 

} 
@Test() 
public void testMethod() { 
    testObject.A(); 

} 

第一个模拟成功的作品,但使用whenNew失败,出现以下错误的第二模拟:

org.powermock.reflect.exceptions.ConstructorNotFoundException: No constructor found in class 'ClassC' with parameter types: [ null ]

如果我使用withArguments(objectA, callback())在那里我有回调的在我的测试执行类,实际的构造函数被调用。

我想模拟构造函数调用并将调用限制在实际构造函数中。我怎样才能做到这一点?

I can not edit the code design since that is out of my scope.

+0

错误明显是说没有在C级发现的构造,所以你不能你whenNew() – want2learn

+0

它说,一个particul没有找到ar类型的构造函数。如果我将用于某个确切值的匹配器更改为实际构造函数。 –

+0

你确定你正在使用**参数** matcher any()吗?换句话说:不要解释你的一半代码 - 而是编辑你的问题,并把它变成一个[mcve],我们有**所有**事实到最坏的情况自己运行这些东西! – GhostCat

回答

0

总之,你的错误由于2点通用any()的匹配使用。

当您使用.withArguments(...)和设置都为any()这意味着 .withArguments(null, null)(因为任何()可以搭配几乎任何东西,包括空值)最终折叠作为一个零和反射API(这PowerMock很大程度上依赖于)失败为ClassC(null)发现合适的构造函数。

您可以检查出的org.powermock.api.mockito.internal.expectation.AbstractConstructorExpectationSetup<T> source,没有工作

来修复这个问题考虑使用任何.withAnyArguments()如果你不在乎PARAM类型的源和磕碰所有可用的构造函数OR指定更具体的类型同时采用any()像这样 whenNew(ClassC.class).withArguments(any(ClassA.class), any(Callback.class))