Created
September 8, 2015 21:53
-
-
Save ctigeek/000577cd4ac6829cd7ab to your computer and use it in GitHub Desktop.
Mocking a method that takes an action which Sets a Threading.ManualResetEvent
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| //code from NServicebus.... | |
| public static int WaitForReturn(this ICallback callback, TimeSpan timeout) | |
| { | |
| int returnValue = 0; | |
| ManualResetEvent handle = new ManualResetEvent(false); | |
| callback.Register((Action<int>) (i => | |
| { | |
| returnValue = i; | |
| handle.Set(); | |
| })); | |
| handle.WaitOne(timeout); | |
| return returnValue; | |
| } | |
| //In order to mock this.... | |
| var messageCallback = new Mock<ICallback>(); | |
| messageCallback.Setup(m => m.Register(It.IsAny<Action<int>>())) | |
| //this has to be on a separate thread or else it will block forever. | |
| .Callback<Action<int>>(a => System.Threading.ThreadPool.QueueUserWorkItem(state => | |
| { | |
| System.Threading.Thread.Sleep(5); //You have to give the original thread time to execute the handle.waitone. | |
| a(123); | |
| })); | |
| //Set up the queue mock so it returns the ICallback mock. | |
| messageDispatcher.Setup(md => md.Queue(It.IsAny<IMessage[]>())) | |
| .Returns(messageCallback.Object); | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment