Skip to content

Instantly share code, notes, and snippets.

@adamjasinski
Last active December 10, 2015 00:38
Show Gist options
  • Save adamjasinski/4352462 to your computer and use it in GitHub Desktop.
Save adamjasinski/4352462 to your computer and use it in GitHub Desktop.
xUnit TheoryAttribute specialization with data disposal facility
using System;
using System.Collections.Generic;
using System.Linq;
using Xunit.Extensions;
using Xunit.Sdk;
namespace Prototypes.Xunit.Extensions;
{
/// <summary>
/// Theory that disposes data items after finishing the execution.
/// See also proposed 'Theory Data Disposal facility' work item on http://xunit.codeplex.com/workitem/9798
/// </summary>
class TheoryWithDataDisposalAttribute : TheoryAttribute
{
protected override IEnumerable<ITestCommand> EnumerateTestCommands( IMethodInfo method )
{
foreach ( var command in base.EnumerateTestCommands( method ) )
{
yield return command;
var theoryCommand = command as TheoryCommand;
if ( theoryCommand != null )
yield return new DisposeCommand( method, theoryCommand.Parameters );
}
}
class DisposeCommand : TestCommand
{
readonly IDisposable[] _disposables;
public DisposeCommand( IMethodInfo method, IEnumerable<object> dataItems )
: base( method, MethodUtility.GetDisplayName( method ), MethodUtility.GetTimeoutParameter( method ) )
{
_disposables = dataItems
.OfType<IDisposable>()
.Where( x => x != null ).ToArray();
}
public override MethodResult Execute( object testClass )
{
foreach ( var disposable in _disposables )
disposable.Dispose();
return new PassedResult( testMethod, DisplayName );
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment