вызов метода mock возвращает ноль - PullRequest
0 голосов
/ 25 октября 2019

У меня есть следующий метод, который очищает неполный адрес. Например: Say AddressLine1 = "800 Wash s st", тогда возвращается "800 Washington s st". Для этого метода я использую AddressScrubbingApi через ApiClientHelper. Следовательно, в моем текущем коде у меня есть зависимость ApiClientHelper.

public async Task<PartyAddress> ScrubAddress(PartyAddress addressToBeScrubbed)
{
if (_baseApiClient == null)
{
 SetApiClient(new BaseApiClient());
}
AddressScrubbingRequest addressObject = BuildRequestObject(addressToBeScrubbed);
string path = "/v1/addresses/actions/scrub";
//this is the baseApiClient that is to be injected as mock in unit test
var scrubbedAddress = await _baseApiClient.CallPostApiAsync<AddressScrubbingResponse>(AddressScrubbingApiKey, path, addressObject);
    if (scrubbedAddress.Status == ValidationStatus.HighProbabilityMatch.ToString())
     {
      addressToBeScrubbed.Addr1 = scrubbedAddress.Primary;
      addressToBeScrubbed.Addr2 = scrubbedAddress.Secondary;        
      addressToBeScrubbed.StreetNumber = scrubbedAddress.HouseNumber;
      addressToBeScrubbed.City = scrubbedAddress.City;
      addressToBeScrubbed.StateProv = StateCode.GetId(scrubbedAddress.State).HasValue ? AcordConversionHelper.CreateCodeValue(scrubbedAddress.State, StateCode.GetId(scrubbedAddress.State)) : AcordConversionHelper.CreateCodeValue(null, null);
      addressToBeScrubbed.PostalCode = scrubbedAddress.Zip5;
      addressToBeScrubbed.ZipExtension = scrubbedAddress.Zip4;
      addressToBeScrubbed.StreetName = scrubbedAddress.Name;
     //some more fields here
     addressToBeScrubbed.SuccessfullyScrubbedDtTm = System.DateTime.Now;
     }
     else if (scrubbedAddress.Status == ValidationStatus.MultipleMatches.ToString() || scrubbedAddress.Status == ValidationStatus.LowProbabilityMatch.ToString())
     {
      addressToBeScrubbed.StreetName = scrubbedAddress.Name;
      //partyAddress.Address.StreetType = scrubbedAddress.StreetTypeDesignator;
      //PreDirection=scrubbedAddress.PreDirection;
      //PostDirection=scrubbedAddress.PostDirection;
      addressToBeScrubbed.SuccessfullyScrubbedDtTm = System.DateTime.Now;
      }
   return addressToBeScrubbed;
}

Вот модульный тест, который я пробовал до сих пор

public static async Task ConvertFromAcordScrubAddressTest()
{
TestHelper.InitializeAcordConversionMetadata();
ConvertFromAcord.PartyConversion partyConversion = new ConvertFromAcord.PartyConversion();
Address address = TestHelper.SetupPartyAddress();
var requestAddress = TestHelper.SetupRequestAddress(address);
var mock = new Mock<IBaseApiClient>();
partyConversion.SetApiClient(mock.Object);
string path = "/v1/addresses/actions/scrub";
mock.Setup(m => m.CallPostApiAsync<AddressScrubbingResponse>(AddressScrubbingApiKey, path, requestAddress))
                .ReturnsAsync(new AddressScrubbingResponse
                {
                    Status = "MultipleMatches",
                    Message = "Multiple matches were found for the address you entered.  Normally this is a result of not including East, West, North, or South in the address line.",
                    IsPhysicalMatch = false,
                    Primary = "800 N WASHINGTON ST",
                    Secondary = string.Empty,
                    City = "VAN WERT",
                    State = "OH",
                    Zip5 = "45891",
                    Zip4 = "1269",
                    HouseNumber = "800",
                    PostDirection = string.Empty,
                    Name = "Washington",
                    StreetTypeDesignator = "St",
                    PreDirection = "N",
                    PoBoxNumber = string.Empty,
                    UnitTypeDesignator = string.Empty,
                    UnitNumber = string.Empty,
                    PrivateMailBox = string.Empty
                });
var scrubbedAddress=await  partyConversion.ScrubAddress(address);

 // Assert.PropertyChanged(address, nameof(address.Addr1), t=>t.partyConversion.ScrubAddress(address));
// this is to test whether Addr1 property is set when a call to the partyConversion.ScrubAddress(address); is made in above.
}

Мои вопросы следующие

  1. Когда передается мой макет, в методе partyConversion.ScrubAddress() он возвращает ноль. Таким образом, строка после этого выбрасывает объектную ссылку на нулевое исключениеЯ неправильно создаю макет?
  2. Как проверить этот метод для проверки изменений свойств?

1 Ответ

0 голосов
/ 25 октября 2019

Кажется, что переданный макет requestAddress не равен , чем созданный addressObject с помощью кода AddressScrubbingRequest addressObject = BuildRequestObject(addressToBeScrubbed);

Вы можете определить этот последний параметр как It.IsAny<AddressScrubbingRequest>() во время Setupв этом случае будет вызван ваш фиктивный метод.

mock.Setup(m => m.CallPostApiAsync<AddressScrubbingResponse>
                 (AddressScrubbingApiKey, path, It.IsAny<AddressScrubbingRequest>()))
...