【问题标题】:How can I use Mockito to mock a method of an instantiated class?如何使用 Mockito 模拟实例化类的方法?
【发布时间】:2019-05-22 10:51:57
【问题描述】:

我需要为此 CustomerEnrollmentSoapServiceImpl 服务编写一个测试用例。如何模拟enrollExtStub.enrollExt() 方法

@Service
public class CustomerEnrollmentSoapServiceImpl implements CustomerEnrollmentSoapService {


    @Override
    public EnrollExtStub.EnrollExtResponse enrollMember(LoyalHeaders loyalHeaders, EnrollExtStub.Data_type0 enrollMember)  {
        EnrollExtStub enrollExtStub = new EnrollExtStub();

        EnrollExtStub.EnrollExtResponse enrollExtResponse = enrollExtStub.enrollExt(enrollExt, messageHeader);
        return enrollExtResponse;
    }
}

【问题讨论】:

  • 这种场景称为模拟方法本地实例化。使用 powermockito 而不是 mockito。
  • @kswaughs 你能把示例代码作为答案吗
  • 添加了我的示例代码。

标签: spring-boot junit mocking mockito


【解决方案1】:

没有干净的方法可以做到这一点。假设你真的想测试这个,它看起来像生成的代码,我可能不会测试,我测试了很多。但是,如果你这样做,你需要一个接缝。如果EnrollExtStub 是无状态的,或者在其上调用enrollExt 不会更改内部数据,您可以将其设为自动装配的bean。

@Service
public class CustomerEnrollmentSoapServiceImpl implements CustomerEnrollmentSoapService {
   @Autowired
   private EnrollExtStub enrollExtStub;

    @Override
    public EnrollExtStub.EnrollExtResponse enrollMember(LoyalHeaders loyalHeaders, EnrollExtStub.Data_type0 enrollMember)  {

        EnrollExtStub.EnrollExtResponse enrollExtResponse = enrollExtStub.enrollExt(enrollExt, messageHeader);
        return enrollExtResponse;
    }
}

然后让EnrollExtStub成为一个豆子

@Configuration
public class EnrollExtStubConfig {

    @Bean
    public EnrollExtStub enrollExtStub(){
        return new EnrollExtStub();
    }
}

然后在你的测试中

@RunWith(MockitoJUnitRunner.class)
public class CustomerEnrollmentSoapServiceImplTest {

    @InjectMocks
    private CustomerEnrollmentSoapServiceImpl service;

    @Mock
    private EnrollExtStub enrollExtStub;
...

或者,您可以让它直接调用另一个类似于EnrollExtStubConfig 的类,它会在其中创建EnrollExtStub,并且您可以模拟该类以返回您的模拟EnrollExtStub

【讨论】:

    【解决方案2】:
    @RunWith(PowerMockRunner.class)
    @PrepareForTest({CustomerEnrollmentSoapServiceImpl.class})
    public class CustomerEnrollmentSoapServiceImplTest  {
    
      @Test
      public void enrollMemberTest() throws Exception {
    
        EnrollExtStub enrollExtStubMock = PowerMockito.mock(EnrollExtStub.class);
        PowerMockito.whenNew(EnrollExtStub.class).thenReturn(enrollExtStubMock);
    
        PowerMockito.when(enrollExtStubMock.enrollExt(Matchers.anyClass(enrollExt.class), Matchers.anyClass(MessageHeader.class))
           .thenReturn(enrollExtResponse);
     }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-12-24
      • 1970-01-01
      • 2015-07-19
      • 2020-12-08
      • 1970-01-01
      • 2017-10-17
      • 1970-01-01
      相关资源
      最近更新 更多