2 years ago

#63747

test-img

user584018

xUnit AutoFixture throwing error with data annotation attribute

I am using AutoFixture.Xunit2 and try to generate auto data for my model class which has enum with regular expression data annotation as well.

public enum TypeEnum
{
    [Display(Name = "Fix")]
    On = 0,
    [Display(Name = "Not Fix")]
    Off = 1
}

public class DataModel
{
    [RegularExpression("Fix|Not Fix", ErrorMessage = "Invalid")]
    public TypeEnum Type { get; set; }
    public string Id { get; set; }
}

Now I am using [AutoData] attribute to generate data for my DataModel,

public class ServiceTest
{
    public readonly Service _sut;
    private readonly Mock<IServiceClient> _serviceClientMock = new Mock<IServiceClient>();
    private readonly Mock<ILogger<Service>> _loggerMock = new Mock<ILogger<Service>>();
    public ServiceTest()
    {
        _sut = new Service(_serviceClientMock.Object, _loggerMock.Object);
    }

    [Theory]
    [AutoData]
    public async Task Do_Test_For_DoMethod(DataModel model)
    {
        await _sut.DoMethod(model);
    }
}

But the test is fail with below error,

System.ArgumentException: Object of type 'System.String' cannot be converted to type 'Library.API.Data.Models.TypeEnum'.

  1. How to fix this? If I removed RegularExpression attribute from the model class, it's works.

  2. Plus how to make use to AutoFixture AtoMoq feature here to get rid of Service class creation with constructor?

Update I tried this way where TypeEnum I am providing through InlineData and Id is auto generated, any other way?

[Theory]
[InlineData(TypeEnum.On)]
[InlineData(TypeEnum.Off)]
public async Task Do_Test_For_DoMethod(TypeEnum typeEnum)
{
    var model = new Fixture().Build<DataModel>()
    .With(a => a.Type, typeEnum).Create();

    await _sut.DoMethod(model);
}

c#

xunit

autofixture

0 Answers

Your Answer

Accepted video resources