c# - How to mock out call to service in an integration test? -
let want perform integration test on api controller method looking this:
public async task<iactionresult> get(guid id) { try { if (id == guid.empty) { return new badrequestobjectresult("id not valid"); } var result = await _filestorageservice.getfileurlwithaccesskey(id); if (result == null) { return new notfoundobjectresult("could not find file given id"); } var document = new document() { url = result }; return ok(document); } catch (storageexception storageexception) { switch (storageexception.requestinformation.httpstatuscode) { case 404: return json(statuscode(404)); default: return json(statuscode(500)); } } catch (exception) { return json(statuscode(500)); } }
my integration test looks this(i have started implement it, first test not completed):
public class documentscontrollertest : iclassfixture<testserverfixture> { private readonly httpclient client; public documentscontrollertest(testserverfixture fixture) { client = fixture.client; } [fact] public async task get_whencallednotexistingfileid_shouldreturn404statuscode() { var nonexistentid = guid.newguid(); var response = await client.getasync($"/documents/{nonexistentid}"); } }
in api controller method want mock out call _filestorageservice.getfileurlwithaccesskey(id);
i have tried mock out call __filestorageservice, mocking out interface ifilestorageservice
public class testserverfixture { /// <summary> /// test fixture can used test classes want httpclient /// can shared across tests in class. /// </summary> public httpclient client { get; set; } private readonly testserver _server; public testserverfixture() { var webhostbuilder = new webhostbuilder() .useenvironment("unittest") .usestartup<startup>() .configureservices(services => { services.tryaddscoped(serviceprovider => a.fake<ifilestorageservice>()); }); _server = new testserver(webhostbuilder); client = _server.createclient(); } public void dispose() { client.dispose(); _server.dispose(); } }
but dont think call var result = await _filestorageservice.getfileurlwithaccesskey(id);
being mocked out correct in testserverfixture
class, because test code keep going code , getting error because have not provided parameters filestorageservice. can in scenario mock out call service completely, dont go code?
just because create fake service doesn't mean mocking framework knows return method call.
i'm not familiar fakeiteasy think want this:
var fakefilestorageservice = a.fake<ifilestorageservice>(); a.callto(() => fakefilestorageservice.getfileurlwithaccesskey(a<guid>.ignored)) .returns(fakeresult);
where fakeresult want return test.
Comments
Post a Comment