c# - Mocking Task.Delay -
i have method following line: await task.delay(waittime).configureawait(false);
i there strategy avoid waiting few seconds when unit testing , instead verify tried wait specific number of seconds.
for instance, there way inject additional parameter method in (contrived) example inject mocked object of fictitious itaskwaiter
interface:
// arrange var mockwait = new mock<itaskwaiter>(mockbehavior.strict); mockwait.setup(w => w.delay(it.is<timespan>(t => t.totalseconds == 2))); // act myobject.mymethod(mockwait.object); // assert mockwait.verify();
you can define "delayer" interface this:
public interface iasyncdelayer { task delay(timespan timespan); }
and can provide following implementation production code:
public class asyncdelayer : iasyncdelayer { public task delay(timespan timespan) { return task.delay(timespan); } }
now, class this:
public class classundertest { private readonly iasyncdelayer asyncdelayer; public classundertest(iasyncdelayer asyncdelayer) { this.asyncdelayer = asyncdelayer; } public async task<int> methodundertest() { await asyncdelayer.delay(timespan.fromseconds(2)); return 5; } }
this basic application of dependency injection. basically, extracted logic of asynchronously waiting different class , created interface enable polymorphism.
in production, compose object this:
var myclass = new classundertest(new asyncdelayer());
now, in test can create fake delayer returns this:
[testmethod] public async task testmethod1() { var mockwait = new mock<iasyncdelayer>(); mockwait.setup(m => m.delay(it.isany<timespan>())).returns(task.fromresult(0)); var sut = new classundertest(mockwait.object); var result = await sut.methodundertest(); assert.areequal(5, result); }
Comments
Post a Comment