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.