2017-12-18 158 views
0

注意:为了预期那些希望指出具有构造其内部对象的代码的不良设计,而不是通过依赖注入,或容易被嘲笑的工厂;我正在为遗留代码编写测试,其中将代码重构为更现代的设计不是一种选择。使用PowerMockito如何验证构造函数是否被调用,以及一组特定的参数

我有一个命令方法,当它执行时将在类MyObjectWrapper中构建三个对象,该对象依赖于另一个类MyObject。在测试中,这两个类和6个对象都被嘲笑。请看下面的代码:

@RunWith(PowerMockRunner.class) 
@PrepareForTest(MyCommand.class) 
public class MyCommandTest { 

    @Mock public MyObject objectOne; 
    @Mock public MyObject objectTwo; 
    @Mock public MyObject objectThree; 

    @Mock public MyObjectWrapper wrapperOne; 
    @Mock public MyObjectWrapper wrapperTwo; 
    @Mock public MyObjectWrapper wrapperThree; 

    private MyCommand command; 

    @Before public void beforeEach() { 
     command = new MyCommand(); 
     MockitoAnnotations.initMocks(this); 
     initialiseWrapper(wrapperOne, objectOne, true, false); 
     initialiseWrapper(wrapperTwo, objectTwo, false, false); 
     initialiseWrapper(wrapperThree, objectThree, true, true); 
    } 

    private void initialiseWrapper(MyObjectWrapper wrapperMock, MyObject objMock, boolean option1, boolean option2) { 
     wrapperMock = PowerMockito.mock(MyObjectWrapper.class); 
     PowerMockito.whenNew(MyObjectWrapper.class) 
      .withParameters(MyObject.class, Boolean.class, Boolean.class) 
      .withArguments(objMock, option1, option2) 
      .thenReturn(wrapperMock); 
    } 

    @Test public void testConstructoresCalled() throws Exception { 
     command.execute(); 

     VERIFY constructor with arguments: objectOne, true, false 
     VERIFY constructor with arguments: objectTwo, false, false 
     VERIFY constructor with arguments: objectThree, true, true 
    } 
} 

我知道,我可以证实,构造与所谓的3倍:

PowerMockito.verifyNew(MyObjectWrapper.class, times(3)); 

不过,我需要确认的构造被称为,在经过三个参数。是否有可能做到这一点?

回答

0

PowerMockito.html#verifyNew返回ConstructorArgumentsVerification,所以使用返回的对象,看到ConstructorArgumentsVerification javadoc

+0

将返回一个对象,我可以证实,发生了什么时,3个构造函数的调用? –

+0

你必须验证每个电话(如果我没记错的话) – 2017-12-18 13:58:21

+0

谢谢。 PowerMockito.verifyNew(MyObjectWrapper.class).withArguments(objectOne,true,false);是正确的解决方案。 –

相关问题