我正在尝试模拟一个调用第三方服务的对象,但在执行我的测试用例时没有使用我的模拟类。相反,它会对第三方服务进行实际调用。有人知道为什么吗?
我的when()then()
有效。
这是我的集成测试类:
public class CheckoutStepsAddressITest extends AbstractITest {
//Class to be tested
@Autowired private CheckoutStepsAddressUtil checkoutStepsAddressUtil;
//Dependencies (will be mocked)
private CustomerService customerService;
//Test data
private AddressResponse addressResponse;
private CheckoutAddressView checkoutAddressView;
private AddressView addressView;
@Before
public void setup() {
addressResponse = createAddressResponse();
customerService = mock(CustomerService.class);
checkoutAddressView = new CheckoutAddressView();
checkoutAddressView.setNewAddress(createAddressView());
addressView = createAddressView();
}
public AddressResponse createAddressResponse() {
AddressDto addressDto = new AddressDto();
addressDto.setFirstName("tin");
addressDto.setLastName("tin");
addressDto.setCity("US");
addressDto.setZipCode("10212");
addressDto.setStreet1("street 1");
addressDto.setStreet2("street 2");
addressDto.setCountryCode("DE");
addressDto.setCompany("abc");
AddressResponse response = new AddressResponse();
response.setAddresses(Collections.singletonList(addressDto));
ValidationResult validationResult = new ValidationResult();
validationResult.setValidationStatus(JsonResponseStatus.OK);
response.setValidationResult(validationResult);
return response;
}
public AddressView createAddressView() {
AddressView addressView = new AddressView();
addressView.setFirstName("tin");
addressView.setLastName("tin");
addressView.setCity("US");
addressView.setZipCode("10212");
addressView.setStreet1("street 1");
addressView.setStreet2("street 2");
addressView.setCountryCode("DE");
addressView.setCompany("abc");
return addressView;
}
@Test
public void testCheckForCustomerAndUpdateAddress() throws UnexpectedException {
Mockito.when(customerService.updateAddress(addressView, UUID.randomUUID(), "BILLINGADDRESS", new JsonMessages())).thenReturn(addressResponse);
checkoutStepsAddressUtil.checkForCustomerAndUpdateAddress(UUID.randomUUID().toString(), checkoutAddressView, new JsonMessages(), UUID.randomUUID());
}
}
这是实际的测试方法
@Component
public class CheckoutStepsAddressUtil {
private static final Logger LOG = LoggerFactory.getLogger(CheckoutStepsAddressUtil.class);
@Autowired private CustomerService customerService;
@Autowired private UrlBuilder urlBuilder;
@Autowired private CustomerViewBuilder customerViewBuilder;
@Autowired private CheckoutViewBuilder checkoutViewBuilder;
@Autowired private CheckoutUtil checkoutUtil;
@Autowired private OfferService offerService;
public AddressView checkForCustomerAndUpdateAddress(String addressId, CheckoutAddressView checkoutView, JsonMessages messages, UUID customerId) throws UnexpectedException {
LOG.info("Entering");
AddressView addressView = null;
//check if the customer Id is null, if yes then return the error response else proceed to update
if (customerId == null) {
messages.addError(CheckoutStepAjaxControllerConstants.SHOP_CHECKOUT_ADDRESSES_MISSING_OFFER_OR_CUSTOMER);
LOG.info("Failed to store address because of missing customer");
} else {
//Trims the empty field values to null and proceed to update
checkoutUtil.trimEmptyAddressFieldsToNull(checkoutView);
addressView = updateAddressAndCheckAddressValidationResult(addressId, checkoutView, messages, customerId);
}
return addressView;
}
/**
* Calls Customer service to update the address and then checks the Validation Result with status`ERROR`
* and adds them to `JsonMessages`
*
* @param addressId id of the address to be updated
* @param checkoutView view that has the address to update
* @param messages
* @param customerId
* @return AddressView
* @throws UnexpectedException
*/
private AddressView updateAddressAndCheckAddressValidationResult(String addressId, CheckoutAddressView checkoutView, JsonMessages messages, UUID customerId) throws UnexpectedException {
AddressView address = checkoutView.getNewAddress();
address.setAddressId(addressId);
String identifier = OfferAddressType.NEW.toLower() + ADDRESS;
AddressResponse addressResponse = customerService.updateAddress(address, customerId, identifier, messages);
checkAddressValidationResponseFromCustomer(messages, identifier, addressResponse);
return address;
}
更新:通过这样做解决了我的问题
@RunWith(MockitoJUnitRunner.class)
public class CheckoutStepsAddressUtilITest extends AbstractITest {
//Mock all the dependencies here
@Mock
private CustomerService customerService;
@Mock
private UrlBuilder urlBuilder;
@Mock
private CustomerViewBuilder customerViewBuilder;
@Mock
private CheckoutViewBuilder checkoutViewBuilder;
@Mock
private CheckoutUtil checkoutUtil;
@Mock
private OfferService offerService;
//Injects all the dependencies
@InjectMocks
private CheckoutStepsAddressUtil checkoutStepsAddressUtil;
//Test data
private AddressResponse addressResponse;
private CheckoutAddressView checkoutAddressView;
private AddressView actualAddressView;
@Before
public void setup() {
addressResponse = createAddressResponse();
checkoutAddressView = new CheckoutAddressView();
checkoutAddressView.setNewAddress(createAddressView());
actualAddressView = createAddressView();
}
@Test
public void testCheckForCustomerAndUpdateAddress() throws UnexpectedException {
Mockito.when(customerService.updateAddress(any(), any(), anyString(), any())).thenReturn(addressResponse);
AddressView expectedAddressView = checkoutStepsAddressUtil.checkForCustomerAndUpdateAddress(UUID.randomUUID().toString(), checkoutAddressView, new JsonMessages(), UUID.randomUUID());
assertNotNull(expectedAddressView);
assertEquals(actualAddressView.getFirstName(), expectedAddressView.getFirstName());
}
被调用的客户服务不是你模拟的客户服务。
测试中服务的自动连线注释将 CheckoutStepsAddressUtil 中具有相同注释的所有服务连接。这意味着当你运行测试时,Spring 无法知道它应该用你的模拟替换 customerService 实例。因此,调用实际服务。
您需要一种方法将模拟服务注入要测试的服务中。
一种方法是通过 ReflectionTestUtils,在实际调用测试方法之前将此行添加到测试中应该可以解决问题:
ReflectionTestUtils.setField(checkoutStepsAddressUtil, "customerService", customerService);
请注意,在这种情况下,您仍在自动连接服务的其他依赖项,因此其他调用可能仍然存在问题。
when.then 中使用的一些对象与在执行期间实际传递给此方法的对象不同。我会在这里玩通配符:
@Test
public void testCheckForCustomerAndUpdateAddress() throws UnexpectedException {
UUID uuid = UUID.randomUUID();
Mockito.when(customerService.updateAddress(
eq(addressView), eq(uuid), eq("BILLINGADDRESS"), any(JsonMessages.class))
.thenReturn(addressResponse);
checkoutStepsAddressUtil.checkForCustomerAndUpdateAddress(uuid.toString(),checkoutAddressView, new JsonMessages(), uuid );
}
使用: Mockito.any(), Mockito.eq()
;