Search code examples
c#extension-methodsassertxunit.net

Extending XUnit Assert class with new asserts


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?


Solution

  • 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(...);