Skip to content

Commit

Permalink
Make It.IsAny, It.IsNotNull work for COM types
Browse files Browse the repository at this point in the history
Testing a COM object's type using `IsAssignableFrom` can report false
negatives. .NET might only see the generic RCW type `__ComObject` in-
stead of the COM interface type. The `is` operator on the other hand
appears to be performing `QueryInterface` for COM objects to get the
right result.

Since `is` and `Type.IsAssignableFrom` work somewhat differently (see
https://stackoverflow.com/q/44368313/240733), the previous type check
is left in place for all objects *except* COM objects; for those, the
`is`-based check is used instead. This distinction should reduce the
likelihood of introducing a breaking change.
  • Loading branch information
stakx committed Jun 11, 2017
1 parent b4829ff commit f735b3e
Showing 1 changed file with 13 additions and 0 deletions.
13 changes: 13 additions & 0 deletions Source/It.cs
Original file line number Diff line number Diff line change
Expand Up @@ -45,6 +45,9 @@
using System.Text.RegularExpressions;
using System.Diagnostics.CodeAnalysis;
using System.Reflection;
#if !NETCORE
using static System.Runtime.InteropServices.Marshal;
#endif

namespace Moq
{
Expand All @@ -55,15 +58,25 @@ public static class It
public static TValue IsAny<TValue>()
{
return Match<TValue>.Create(
#if !NETCORE
value => value == null || (IsComObject(value) ? value is TValue
: typeof(TValue).IsAssignableFrom(value.GetType())),
#else
value => value == null || typeof(TValue).IsAssignableFrom(value.GetType()),
#endif
() => It.IsAny<TValue>());
}

/// <include file='It.xdoc' path='docs/doc[@for="It.IsNotNull"]/*'/>
public static TValue IsNotNull<TValue>()
{
return Match<TValue>.Create(
#if !NETCORE
value => value != null && (IsComObject(value) ? value is TValue
: typeof(TValue).IsAssignableFrom(value.GetType())),
#else
value => value != null && typeof(TValue).IsAssignableFrom(value.GetType()),
#endif
() => It.IsNotNull<TValue>());
}

Expand Down

0 comments on commit f735b3e

Please sign in to comment.