简体   繁体   中英

How to add unit tests using Moq and xUnit in this specific scenario?

I have this method in my data/service layer. We are commencing the usage of xUnit and MoQ for unit testing. We use Autofac as our IoC container.

How to set up a unit test for this method using xUnit and MoQ ? Request specific code illustration with usage of Fake (if needed)

public async Task<AddressModel> AddAddress(string useridKey, AddressModel addressModel)
{
    IAddress address = AddressConverters.ToIAddressFromAddressModel(addressModel);
    IAddress newAddress = await _userManager.AddShippingAddressAsync(userKey, address).ConfigureAwait(false);
    return AddressConverters.ToAddressModel(newAddress);
}

You need to inject a mock user manager then do something like

mockUserManager.Setup(arg=>arg.AddShippingAddressAsync(It.Is<string>, It.Is<IAddress>))
    .ReturnsAsync(myNewAddressWhateverYouWantToReturn);

I'm not 100% about xUnit async support, but it looks like it should be something like

[Fact]
private async Task TestAddingAddress()
{
    // inject your mock, either here on setup...

    var thingWithAdd = new Foo();  //or inject mock into constructor...
    var newAddress = await thingWithAdd.AddAddress("", new AddressModel());

    // assert something about it....
}

However, I have no idea what some of your functions do, or what dependencies they have, you may need to mock some more things.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM