How is the unit test method that spawns threads?

I am new to TDD, but used it long enough to understand how to use mocks, stubs, dependency injections, control inversion to solve β€œsimilar” problems ... but for some reason I feel very awkward using dependency injection and passing in "IThread" (or similar).

To give it some basic context - I'm trying to add unit tests to an outdated application, and I'm not sure how the unit test class has a constructor that spawns two threads.

The only use case for dependency injection?

If so, what about the functionality that threads bring? As these threads execute during (true) loops, they never exit the loop (unless the application ends). There are reasonable pieces of code inside the loops, and this is the code I really want to experience.

To make things worse, I don’t want to pull all the functions out of loops and into public methods (I only test public methods, since my tests exist in another project), since it will really reduce the ease of using the class elsewhere in the code.

Any suggestions?

+7
c # unit-testing nunit moq
source share
1 answer

Could you translate the functionality into internal methods and use InternalsVisibleTo instead? Even if you really want them to be private, this is a reasonable compromise.

If your threads usually run forever, it is very difficult to check ... and it looks like you really should test "what the threads do" separately, if they do not depend on the individual threads.

One option that is sometimes useful is to have an IScheduler interface IScheduler - ask for an action where it sees fit; a new thread will be created during the creation process, but your test may trigger an action in an existing thread (or in a thread that you controlled in your test code). I'm not sure if this is suitable for your situation here, where the thread will work forever, but you might think about it in other situations.

+5
source share

All Articles