Skip to content
This repository

HTTPS clone URL

Subversion checkout URL

You can clone with HTTPS or Subversion.

Download ZIP
branch: master
Fetching contributors…

Cannot retrieve contributors at this time

file 64 lines (54 sloc) 1.843 kb
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64
using System;
using Microsoft.VisualStudio.TestTools.UnitTesting;


namespace Whathecode.Microsoft.VisualStudio.TestTools.UnitTesting
{
public class AssertHelper
{
/// <summary>
/// Verify whether a certain exception is thrown.
/// Assertion fails when no exception or the wrong exception is thrown.
/// </summary>
/// <typeparam name = "T">The type of expection which is expected to be thrown.</typeparam>
/// <param name = "action">The action to be executed which should throw an exception.</param>
/// <param name = "allowDerivedTypes">Also allow exceptions which derive from the expected exception type.</param>
public static void ThrowsException<T>( Action action, bool allowDerivedTypes = true )
{
Type type = typeof( T );

try
{
action();
}
catch ( Exception e )
{
if ( allowDerivedTypes ? !(e is T) : e.GetType() != type )
{
Assert.Fail( "Incorrect exception is thrown. Expected \"" + type + "\", thrown \"" + e + "\"" );
}

return;
}

Assert.Fail( "Expected exception \"" + type + "\" was not thrown." );
}

public static void IsGarbageCollected<TObject>( ref TObject @object )
where TObject : class
{
Action<TObject> emptyAction = o => { };
IsGarbageCollected( ref @object, emptyAction );
}

public static void IsGarbageCollected<TObject>( ref TObject @object, Action<TObject> useObject )
where TObject : class
{
if ( typeof( TObject ) == typeof( string ) )
{
// Strings are copied by value, and don't leak anyhow.
return;
}

int generation = GC.GetGeneration( @object );
useObject( @object );
WeakReference reference = new WeakReference( @object );
@object = null;

GC.Collect( generation, GCCollectionMode.Forced );
GC.WaitForPendingFinalizers();

Assert.IsFalse( reference.IsAlive );
}
}
}
Something went wrong with that request. Please try again.