我需要为此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;
}
}
答案 0 :(得分: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
。
答案 1 :(得分:1)
@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);
}
}