Single local flow testing methods

I have a method that looks like this:

protected void OnBarcodeScan(BarcodeScannerEventArgs e)
{
    // We need to do this on a seperate thread so we don't block the main thread.
    ThreadStart starter = () => SendScanMessage(e, _scanDelegates);
    Thread scanThread = new Thread(starter);

    scanThread.Start();
}

Then the thread shuts down and executes some logic (and ends the delegate call in my test).

My problem is that my unit test ends before the thread executes. Therefore, my test fails.

I can just add in System.Threading.Thread.Sleep(1000);and hope that the logic does not take more than a second (this should not). But this seems like a hack.

The problem is that I do not want to reveal this stream to the outside world or even to the rest of the classes.

Is there any cool way to find this thread again and wait for it in unit test?

Something like that:

[TestMethod]
[HostType("Moles")]
public void AddDelegateToScanner_ScanHappens_ScanDelegateIsCalled()
{
    // Arrange
    bool scanCalled = false;
    MCoreDLL.GetTopWindow = () => (new IntPtr(FauxHandle));

    // Act
    _scanner.AddDelegateToScanner(_formIdentity, ((evnt) => { scanCalled = true; }));
    _scanner.SendScan(new BarcodeScannerEventArgs("12345678910"));

    // This line is fake!
    System.Threading.Thread.CoolMethodToFindMyThread().Join();

    // Assert
    Assert.IsTrue(scanCalled);
}

I obviously compiled the CoolMethodToFindMyThread method . But are there some reasons for this?

+3
2

, , , , , , , ? , . .

- :

[TestMethod]
[HostType("Moles")]
public void AddDelegateToScanner_ScanHappens_ScanDelegateIsCalled()
{
    // Arrange
    var scanCalledEvent = new ManualResetEvent(false);
    MCoreDLL.GetTopWindow = () => (new IntPtr(FauxHandle));

    // Act
    _scanner.AddDelegateToScanner(_formIdentity, ((evnt) => { scanCalledEvent.Set(); }));
    _scanner.SendScan(new BarcodeScannerEventArgs("12345678910"));

    // Wait for event to fire
    bool scanCalledInTime = scanCalledEvent.WaitOne(SOME_TIMEOUT_IN_MILLISECONDS);

    // Assert
    Assert.IsTrue(scanCalledInTime);
}

- - , , - , . WaitOne , , , .

(: - , true , , true , . .)

, , . ManualResetEvent .

+8

:

-, AutoResetEvent ( ManualResetEvent, ) .

:

//set up stuff

testEvent.WaitOne();

//ensure everything works

testEvent.Set();

, .

, - - .

+1

Source: https://habr.com/ru/post/1778207/


All Articles