I have following problem with testing class library with NUnit
When i call this method from console app or other project it works propertly - App will work as long as listenerThread is running.
public void StartServer(string ListenOnIp, int port, string ServerPFXCertificatePath, string CertPassword, bool VerifyClients)
{
serverCert = new X509Certificate2(ServerPFXCertificatePath, CertPassword, X509KeyStorageFlags.PersistKeySet);
listener = new TcpListener(IPAddress.Parse(ListenOnIp), port);
Thread listenerThread = new Thread(() =>
{
listener.Start();
int connected = 0;
while (listener.Server.IsBound)
{
TcpClient client = listener.AcceptTcpClient();
SSLClient connection = new SSLClient(client, serverCert, VerifyClients, this);
}
connected++;
});
listenerThread.Start();
}
However when i try to call this method from NUnit test method, it behaves like starting fire and forget task - Test completes immediately.
I tried wrapping StartServer method like that
[Test]
public void Test()
{
Task.Run(() =>
{
server.StartServer(IPAddress.Any, 5000, $"{Workspace}\\{ServerWorkspace}\\Server.pfx", "123", false);
}).Wait();
}
and i tried marking test method like this -[Test,RequiresThread] with no result
I could change StartServer to Task and just use Wait() or Wait() for some TaskCompletionSource which completes when listenerThread ends it work,
but I would like to know if there is a better way, preferably without the need to modify StartServer method.
I couldn't find better way to fix this, so i made something like this using
asyncandTaskCompletionSource.My server class fires an event when any transfer method on the server side completes. My idea is to block test method execution as long as server doesn't fire specified event.
This is what i did -
First i needed
TaskCompletionSouce<object> TestEnderin Test ClassEvery
[SetUp]new instance ofTaskCompletionSourceis assigned to TestEnder.Then we use this "Locker" task, which awaits
TestEndercompletion. It has some kind of "TimeOut" mechanism which will completeTestEndereven if something else fails, so test can like in winxp fashion - "Fail successfully" :)Having this i can now successfully test connection methods with test like that -