Question

I'm trying to extend the xUnit assert method by adding some selenium functionality

namespace MyProject.Web.Specs.PageLibrary.Extensions
{
    public static class AssertExtensions
    {
        public static void ElementPresent(this Assert assert, ...)
        {
            if (...)
            {
                throw new AssertException(...);
            }
        }
    }
}

But I get this compile error when I try to use it.

using MyProject.Web.Specs.PageLibrary.Extensions;    
using Xunit;
...

public void DoSomething()
{
    Assert.ElementPresent(...);
}

And the error

Error   5   'Xunit.Assert' does not contain a definition for 'ElementPresent'

Does anyone know if this is possible or where I'm going wrong?

Was it helpful?

Solution 4

You need object intance that will be passed as this argument to extension method. In your case this would be correct syntax

var assert = new Assert();
assert.ElementPresent(...);

But I suppose you don't need or even can't create instance of Assert class.

What you are trying to do is call extension method as static invocation on extended class and that wont work. But why not simply call

 AssertExtensions.ElementPresent(...);

OTHER TIPS

Edit 2 xUnit 2 eventually ended up moving the assertions into a separate assembly altogether. There are both compiled and source only packages of this on NuGet, and the Assert class is partial, so by using the source only version of the package, Assert becomes very easily extensible (in C#, that is).

Edit For more completeness: xUnit 2 removes this extension point and recommends using extension methods along the lines of 'fluent' assertion libraries.


For completeness, here's a description of the "official" way of extending Assert (which surprisingly has not been mentioned at all, despite the fact that Brad Wilson even joined the discussion).

From version 1.5 (according to Brad's blog), xUnit.Extensions has explicit support for this via the Assertions and TestClass classes. It works like this:

TestClass has a property called Assert that is of type Assertions which relays all the methods on Xunit.Assert. Because TestClass.Assert is an instance, you can add methods to it through extension methods on Assertions:

public static class AssertionsExtensions
{
    public static void DeepEquals(this Assertions assertions, XNode expected, XNode actual)
    {
        assertions.True(XNode.DeepEquals(expected, actual)); // You can also use Assert.True here, there's effectively no difference.
    }
}

Now you need to have your test class derive from Xunit.Extensions.TestClass (confusingly, there is also Xunit.TestClass, which is not what you want), and the Assert property will "shadow" the Xunit.Assert type if you don't qualify the name explicitly.

In your test class that derives from TestClass, you can now use

Assert.DeepEquals(expectedXml, actualXml);

The only real difference from a built-in xUnit assertion (apart from the fact that syntax coloring for Assert is that of an identifier, not a type) is that when it fails, you simply get a TrueException, not a specific DeepEqualsException that could hypothetically tell you where the comparison failed. But of course you could build that too in the very same way.

Summary of the solution for xUnit 2. (Worked for me for version 2.1.0 from NuGet.)

Assert is a partial class that you can extend by adding another part. To be able to do that you need to compile the Assert assembly from sources. You can use xunit.assert.source NuGet to get the sources.

The Steps

  1. Remove reference to the xunit.assert NuGet package from the project.
  2. Instead install xunit.assert.source package.
  3. In the Xunit namespace, define public partial class Assert and add your custom asserts there.
  4. In your test project install the xunit.extensibility.execution package (or otherwise there will be a conflict between two different Assert classes and tests won't run becasue the xunit.execution.*.dll will be missing)

Example of a custom assert:

namespace Xunit
{ 
    public partial class Assert
    {
        public static void ArraySegmentEqual<T>(
            T[] expectedSequence, T[] buffer, int offset = 0)
        {
            for (int i = 0; i < expectedSequence.Length; i++)
            {
                int b = i + offset;

                True(buffer[b].Equals(expectedSequence[i]),
                    $"Byte #{b} differs: {buffer[b]} != {expectedSequence[i]}");
            }
        }
    }
}

Note: Other answers and edits also point to the solution, but it took me quite some tome to figure it out from there. Also, I do not claim this is the only or the best option.

Sorry, but you're getting confused (EDIT: and so was I!). xUnit.net's Assert is static and thus cannot have extensions added (although other Assertion libraries do not sue this approach which is why one might expect to use Extension Methods to extend Assert). So in the xUnit.net universe, if you want to add a custom assertion, add a new static class with a different name.

You can make your approach work by changing your class from:

public static class AssertExtensions
{
    public static void ElementPresent(this Assert assert, ...)

to:

public class AssertExtensions : XUnit.Assert
{
    public static void ElementPresent(...)

and then using Brad Wilson's trick of adding:

using Assert = MyProject.Web.Specs.PageLibrary.Extensions.AssertExtensions; 

at the top of any file needing your extensions.

This technique is handy for adding overloads come to think of it....

(The obvious weakness is that you can't have more than one directly accessible via Assert. though)

For xUnit 2+:

1) Add xunit.assert.source Nuget package to the project with extensions.

2) Create partial class definition:

namespace xUnit
{
  public partial class Assert
  {
    public static void ElementPresent(...)
    {
    }
  }
}

The problem is because of a simple encapsulation constraint:

Since the Assert class has the constructor set to protected you can't create an Extension Method for it, because you can't instantiate it.

So in order to extend Assert, you just have to inherit from it:

public class MyExtendedAssert : Assert
{
    public void ElementPresent(...)
    {
        ...
    }
}

And use:

MyExtendedAssert.ElementPresent(...);

I use a simple partial helper where I add That property so that I can easily build extensions anywhere else:

// ReSharper disable once CheckNamespace
namespace Xunit
{
    public partial class Assert
    {
        [CanBeNull]
        public static Assert That => default;
    }
}

Read Premil's answer how to setup the projects.

I was able to get the solution posted by @Premil to work, but I had to reference xunit.core rather than xunit.extensibility.execution.

Sample Visual Studio 2019 solution is located at https://github.com/groberts314/TestXUnitCustomAssertions.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top