Reputation: 7734
I am beginning to look into using White UI testing with XUnit.
The basic structure for my tests is
This works really well when test passes. However, when a test fails, the application is not closed. If multiple tests fail, this leads to lots of opened instances of my application.
To get around this, I use try and finally blocks but it is not very nice.
Is there an alternate option which achieves the same cleanup behaviour but looks a bit nicer? Like a "RunOnAssertFail" method?
[Fact]
public void MainWindowCreated()
{
bool testFailed = false;
Application application = Application.Launch(@"C:\Program\Program.exe");
Window mainWindow = GetWindow(application, "MainWidndow", 500);
try
{
testFailed = true;
mainWindow.Should().NotBe(null, ". Main Widndow could not be found");
testFailed = false;
}
finally
{
if (testFailed)
{
application.Close();
}
}
/*
* Rest of test case
*/
application.Close();
}
private static Window GetWindow(Application application,
string windowName,
int timeoutAfterMilliseconds)
{
Window window = null;
try
{
window = Retry.For(
() => application.GetWindows().First(
windowX => windowX.Title.Trim().Equals(windowName.Trim())),
TimeSpan.FromMilliseconds(timeoutAfterMilliseconds));
}
catch (InvalidOperationException)
{
}
return window;
}
Requires xUnit, White and Fluent Assertions to run.
Upvotes: 2
Views: 2917
Reputation: 8899
What about implementing IDisposable
on your test class and use that to clean up?
Upvotes: 0
Reputation: 7734
After playing around I realised the assertions were it was throwing an exception and not actually asserting.
Therefore to help tidy it up, a try catch block is more appropriate
try
{
mainWindow.Should().NotBeNull("because this window is required for the rest of the test");
}
catch(XunitException)
{
application.Close();
throw;
}
However, this is still not ideal.
Upvotes: 1