best practice to unit test a class that relies on threads

Asked by fourchette

hi,

i'm trying to to test some hardware device connected through COM port.

it seems the best way to communicate with such a device using C# is through the SerialPort class discussed on MSDN there http://msdn.microsoft.com/en-us/library/system.io.ports.serialport.aspx#Mtps_DropDownFilterText
the provided sample code works and is pretty much self explanatory

it pretty much looks like the following

1. in the main thread, instantiate the static SerialPort objet, stuff it with paramaters (baudRate, parity, etc), open the port, then create a new thread to start listening
2. the other thread simply loops on some serialPort.read() and display response on Console as long as a common flag remains true
3. still in the main thread user is prompted for some commands to the sent to the port.
4. if user types in "exit" then the common flag is set to false, second thread .Join() method is called so that it closes gracefully, COM port is closed and then program exits

it's been working more or less. but before going any further, i want to replay such actions with Nunit.

i have read http://nunit.org/index.php?p=requiresThread&r=2.5.5 but it's still pretty obscure to me. i am not sure i'm getting it.

it seems the most appropriate way to do this is by using some sort of trick like this one here :http://stackoverflow.com/questions/41568/whats-the-best-way-to-test-a-method-from-multiple-threads#41572

i have the feeling i have simply to (re)design my custum class handling the multithread operations but i am confused as what is the best approach ? i want some strong and testable code

anyone has any thought share about multi threading tests using Nunit ?

Question information

Language:
English Edit question
Status:
Answered
For:
NUnit Framework Edit question
Assignee:
No assignee Edit question
Last query:
Last reply:
Revision history for this message
Charlie Poole (charlie.poole) said :
#1

RequiresThread simply causes a separate thread to be created or running your test. While it doesn't prevent you from creating other threads within your test, it doesn't help you particularly either. Your problem seems to be broader than just the NUnit feature set so a wider discussion on the nunit-discuss list may give you better results.

Revision history for this message
fourchette (mxda6w895be1qms) said :
#2

i think the whole story has nothing to do with Nunit but more general guidance about to correctly architect/desgin a class doing the multithreading stuff so that it's easily testable....

i'm working on this right now, but it's been a while since my last multi threading application so i'm a bit rusty with all this :)

Can you help with this problem?

Provide an answer of your own, or ask fourchette for more information if necessary.

To post a message you must log in.