Tuesday 15 July 2014

c# - multithreaded unit test - notify calling thread of event to stop sleeping -



c# - multithreaded unit test - notify calling thread of event to stop sleeping -

i wrote test (nunit) test amazon ses email sending functionality should generate bounce notification in amazon sqs queue. poll queue in loop 1 min on new thread wait , verify bounce notification.

i'd increment time few minutes ensure dont miss it. response may come within seconds in case i'd want record how long took , finish test there no point go on waiting 1 time receipt verified.

how can accomplish threading scenario in clean way, , mean without polluting methodinmainapp() test code. in main app should not happen (it should go on polling indefinitely), should stop in test. should pass in threadstart function both entry points doesnt reply question im asking.

[test] public async void sendandlogbounceemailnotification() { thread bouncesthread = startup.methodinmainapp(); bouncesthread.start(); bool success = await _emailservice.sendasync(...); assert.areequal(success, true); //sleep thread 1 min while //bouncesthread polls bounce notifications thread.sleep(60000); } public static thread methodinmainapp() { ... thread bouncesthread = new thread(() => { while (true) { receivemessageresponse receivemessageresponse = sqsbouncesclient.receivemessage(bouncesqueuerequest); if(receivemessageresponse.messages.count > 0) { processqueuedbounce(receivemessageresponse); //done test } } }); bouncesthread.setapartmentstate(apartmentstate.sta); homecoming bouncesthread; }

use monitor class.

instead of thread.sleep(60000), utilize this:

lock (_lockobject) { monitor.wait(_lockobject, 60000); }

then want signal thread continue:

lock (_lockobject) { monitor.pulse(_lockobject); }

of course of study requires adding static readonly object _lockobject = new object() somewhere in class.

i'm not saying overall strategy right approach. seems here, improve unit test method explicitly phone call other method doing work wait , validate response. above should address specific question.

c# multithreading unit-testing nunit

No comments:

Post a Comment