Like Unit test BackgroundWorker C #

I am trying to run a unit test using the following VS test method.

void Get(string name, Action<string> callBack); 

here is the device tester

  [TestMethod] public void Test() { Action<string> cb = name => { Assert.IsNotNull(name); }; var d = new MyClass(); d.Get("test", cb); } 

The only problem is that the internal implementation uses BackgroundWorker, so the callback is called on another thread. Here is the internal implementation.

  public void Get(string name, Action<string> callBack) { callBackString = callBack; GetData(name); } private void GetData(string name) { BackgroundWorker bw = new BackgroundWorker(); bw.DoWork += bw_DoWork; bw.RunWorkerCompleted += bw_RunWorkerCompleted; bw.RunWorkerAsync(name); } private void bw_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e) { //do work here if (null != callBackString) callBackString("ok"); } 

Of course, since Get () returns immediately, the test succeeds and testing stops, so RunWorkerCompleted never starts. I can easily test this with a regular application (WPF) because it works, but I would like to be able to unit test this.

Any ideas? Thanks in advance.

+4
source share
3 answers

Sort of:

 [TestMethod] public void Test() { bool running = true; string result = null; Action<string> cb = name => { result = name; running = false; }; var d = new MyClass(); d.Get("test", cb); while(running) { Thread.Sleep(100); } Assert.IsNotNull(result); } 

Although you probably want to add something there to stop the test from running forever if it doesn't work ...

+7
source

I don’t know the details for C # and BackgroundWorker, but I would do this by introducing an implementation of BackgroundWorker, and during the test use a muted BackgroundWorker, which you can control when it runs and in which thread. If data exchange between two streams is required, then the shaded BackgroundWorker will create a new stream and pause testing until it is completed, if it does not force it to start after the call.

+4
source

I wrote similar code and made it verifiable by following the IAsyncResult design pattern . My unit tests work against the synchronous (blocking) version of the method. Asynchronous methods can be one line each, so I did not write unit tests against them.

0
source

All Articles