Reputation: 143
I am using Moq to pass dependencies to the class I need to test. This is the constructor and method to test:
public class PosPortalApiService : PosPortalApiServiceBase, IPosPortalApiService {
private readonly string _apiEndpoint;
public PosPortalApiService ( IDependencyResolver dependencyResolver,
IOptions<AppSettings> appSettings ) : base ( dependencyResolver ) {
_apiEndpoint = appSettings.Value.ApiEndpoint;
}
public async Task<IEnumerable<IStore>> GetStoresInfo ( string userId ) {
var endpoint = GetEndpointWithAuthorization(_apiEndpoint + StoresForMapEndpoint, userId);
var encryptedUserId = EncryptionProvider.Encrypt(userId);
var result = await endpoint.GetAsync(new {
encryptedUserId
});
return JsonConvert.DeserializeObject<IEnumerable<Store>>(result);
}
GetEndpointWithAuthorisation is in the base class, it calls the DB. How can i approach testing this? I have the following so far:
[Fact]
public void GetStoresInfoReturnsStoresForUser()
{
var mockHttpHandler = new MockHttpMessageHandler();
var mockHttpClient = new HttpClient(mockHttpHandler);
//mockHttpHandler.When("http://localhost/api/select/info/store/*")
// .Respond("application/json", );
AppSettings appSettings = new AppSettings() { ApiEndpoint = "http://localhost" };
var encryptedUserId = EncryptionProvider.Encrypt("2");
var mockDependancyResolver = new Mock<IDependencyResolver>();
var mockIOptions = new Mock<IOptions<AppSettings>>();
IOptions<AppSettings> options = Options.Create(appSettings);
//Arrange
PosPortalApiService ApiService = new PosPortalApiService(mockDependancyResolver.Object, options);
var sut = ApiService.GetStoresInfo("2");
It runs though until the base method call. Should I be providing a Mock response somehow? How would you do approach this test? Thanks.
Upvotes: 0
Views: 93
Reputation: 4607
You can mock the method in the base class (assuming it's either virtual
or abstract
) by making the PosPortalApiService
object a partial mock. (Partial mocks will use the real class behavior except for the parts you mock out). You do this by setting CallBase = true
on the mock object;
var ApiServiceMock = new Mock<PosPortalApiService>(mockDependancyResolver.Object, options)
{CallBase = true};
ApiServiceMock.Setup(x => x.GetEndpointWithAuthorisation(It.IsAny<string>(), It.IsAny<string>())
.Returns(someEndpointObjectOrMockYouCreatedForYourTest);
PosPortalApiService ApiService = ApiServiceMock.Object;
var sut = ApiService.GetStoresInfo("2");
Upvotes: 1