Search code examples
xunit.netautofixtureautomoq

Can AutoFixture be used to generate multiple test cases?


I've started to experiment with AutoFixture. In my research I found that there is this InlineAutoDataAttribute which one could used to generate multiple test cases with varying input arguments (given some requirements). However, InlineAttribute and similarly InlineAutoDataAttribute can only work with compile const data. So I went looking for something like MemberAutoDataAttribute, as MemberDataAttribute would allow me to feed in a collection of non-'compile time const' objects, like a collection of Exception instances. Sadly, this attribute doesn't exist.

Is there some way how I could reuse a test making use of AutoFixture such that it can generate multiple test cases? Could this be achieved with some ICustomization implementation?

Below is an example of the situation I'm describing. Note that MyCustomAutoDataAttribute is just an basic inherited object of AutoDataAttribute that causes the AutoMoqCustomization to be configured for the fixture.

[Theory, MyCustomAutoDataAttribute]
public void FooBar(Exception exception, [Frozen] ISomeInterface)
{
    ...
    ISomeInterface.Setup(i => i.SomeMethod()).Throws(exception);
    ...
}

Solution

  • I found a workable solution to my problem. It feels like a workaround through, but it got the job done for me.

    [Theory]
    [MyCustomInlineAutoData(typeof(CustomException1))]
    [MyCustomInlineAutoData(typeof(CustomException2))]
    public void FooBar(Type exceptionType, [Frozen] Mock<ISomeInterface> interface, [Frozen] IFixture fixture)
    {
        var exception = (Exception) new SpecimenContext(fixture).Resolve(exceptionType)
        interface.Setup(i => i.SomeMethod()).Throws(exception);
    }
    

    with the following definition for the attribute:

    public class MyCustomInlineAutoData : InlineAutoDataAttribute
    {
        public MyCustomInlineAutoData(params object[] values) : base(new MyCustomAutoDataAttribute(), values)
        {
    
        }
    }