{"id":19811049,"url":"https://github.com/accenture/autofixture.xunit2.automock","last_synced_at":"2025-05-01T08:32:24.975Z","repository":{"id":60773429,"uuid":"78831796","full_name":"Accenture/AutoFixture.XUnit2.AutoMock","owner":"Accenture","description":"Autofixture auto-mocking for XUnit2 using a mocking library of your choice.","archived":false,"fork":false,"pushed_at":"2025-04-23T20:26:34.000Z","size":775,"stargazers_count":23,"open_issues_count":2,"forks_count":6,"subscribers_count":29,"default_branch":"master","last_synced_at":"2025-04-23T21:31:38.601Z","etag":null,"topics":["autofixture","fakeiteasy","mock","moq","nsubstitute","xunit"],"latest_commit_sha":null,"homepage":"","language":"C#","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"mit","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/Accenture.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":null,"license":"LICENSE","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null,"zenodo":null}},"created_at":"2017-01-13T08:47:33.000Z","updated_at":"2025-04-18T13:13:12.000Z","dependencies_parsed_at":"2024-02-27T03:44:18.946Z","dependency_job_id":"b9d12d52-5e67-4406-a6d5-e096cb79c7e5","html_url":"https://github.com/Accenture/AutoFixture.XUnit2.AutoMock","commit_stats":null,"previous_names":["objectivityltd/autofixture.xunit2.automock"],"tags_count":20,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/Accenture%2FAutoFixture.XUnit2.AutoMock","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/Accenture%2FAutoFixture.XUnit2.AutoMock/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/Accenture%2FAutoFixture.XUnit2.AutoMock/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/Accenture%2FAutoFixture.XUnit2.AutoMock/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/Accenture","download_url":"https://codeload.github.com/Accenture/AutoFixture.XUnit2.AutoMock/tar.gz/refs/heads/master","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":251847828,"owners_count":21653582,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["autofixture","fakeiteasy","mock","moq","nsubstitute","xunit"],"created_at":"2024-11-12T09:24:33.526Z","updated_at":"2025-05-01T08:32:24.615Z","avatar_url":"https://github.com/Accenture.png","language":"C#","funding_links":[],"categories":[],"sub_categories":[],"readme":"# Objectivity.AutoFixture.XUnit2.AutoMock\n\n[![CI/CD](https://img.shields.io/github/actions/workflow/status/Accenture/AutoFixture.XUnit2.AutoMock/cicd.yml?logo=githubactions\u0026logoColor=white\u0026label=ci%2Fcd)](https://github.com/Accenture/AutoFixture.XUnit2.AutoMock/actions/workflows/cicd.yml) [![codecov](https://codecov.io/gh/Accenture/AutoFixture.XUnit2.AutoMock/branch/master/graph/badge.svg)](https://codecov.io/gh/Accenture/AutoFixture.XUnit2.AutoMock) [![Mutation testing](https://img.shields.io/endpoint?style=flat\u0026label=stryker\u0026logo=stryker\u0026url=https%3A%2F%2Fbadge-api.stryker-mutator.io%2Fgithub.com%2FAccenture%2FAutoFixture.XUnit2.AutoMock%2Fmaster)](https://dashboard.stryker-mutator.io/reports/github.com/Accenture/AutoFixture.XUnit2.AutoMock/master) [![qodana](https://img.shields.io/github/actions/workflow/status/Accenture/AutoFixture.XUnit2.AutoMock/qodana.yml?style=flat\u0026logo=resharper\u0026label=qodana)](https://github.com/Accenture/AutoFixture.XUnit2.AutoMock/actions/workflows/qodana.yml) [![License: MIT](https://img.shields.io/github/license/Accenture/AutoFixture.XUnit2.AutoMock?label=license\u0026color=brightgreen)](https://opensource.org/licenses/MIT) [![fossa](https://app.fossa.com/api/projects/git%2Bgithub.com%2FObjectivityLtd%2FAutoFixture.XUnit2.AutoMock.svg?type=shield)](https://app.fossa.com/projects/git%2Bgithub.com%2FObjectivityLtd%2FAutoFixture.XUnit2.AutoMock?ref=badge_shield)\n\nAccelerates preparation of mocked structures for unit tests under  [XUnit2](http://xunit.github.io/) by configuring [AutoFixture](https://github.com/AutoFixture/AutoFixture) data generation to use a mocking library of your choice. Gracefully handles recursive structures by omitting recursions.\n\nIt provides the following mocking attributes:\n\n- AutoMockData\n- InlineAutoMockData\n- MemberAutoMockData\n\n***\n\n## Supported mocking libraries\n\n| Mocking library                                           | Corresponding NuGet package |\n| ---------------------------------------------------------:|:--------------------------- |\n| [Moq](https://github.com/moq/moq4)                        | [![AutoMoq](https://img.shields.io/nuget/v/Objectivity.AutoFixture.XUnit2.AutoMoq.svg?logo=nuget\u0026style=flat-square\u0026label=AutoMoq)![Downloads](https://img.shields.io/nuget/dt/Objectivity.AutoFixture.XUnit2.AutoMoq.svg?style=flat-square\u0026label)](https://www.nuget.org/packages/Objectivity.AutoFixture.XUnit2.AutoMoq/) |\n| [NSubstitute](https://github.com/nsubstitute/NSubstitute) | [![AutoNSubstitute](https://img.shields.io/nuget/v/Objectivity.AutoFixture.XUnit2.AutoNSubstitute.svg?logo=nuget\u0026style=flat-square\u0026label=AutoNSubstitute)![Downloads](https://img.shields.io/nuget/dt/Objectivity.AutoFixture.XUnit2.AutoNSubstitute.svg?style=flat-square\u0026label)](https://www.nuget.org/packages/Objectivity.AutoFixture.XUnit2.AutoNSubstitute/) |\n| [FakeItEasy](https://github.com/FakeItEasy/FakeItEasy)    | [![AutoFakeItEasy](https://img.shields.io/nuget/v/Objectivity.AutoFixture.XUnit2.AutoFakeItEasy.svg?logo=nuget\u0026style=flat-square\u0026label=AutoFakeItEasy)![Downloads](https://img.shields.io/nuget/dt/Objectivity.AutoFixture.XUnit2.AutoFakeItEasy.svg?style=flat-square\u0026label)](https://www.nuget.org/packages/Objectivity.AutoFixture.XUnit2.AutoFakeItEasy) |\n\n## Attributes\n\n### AutoMockData\n\nProvides auto-generated data specimens generated by [AutoFixture](https://github.com/AutoFixture/AutoFixture) with a mocking library as an extension to xUnit.net's `Theory` attribute.\n\n#### Arguments\n\n- IgnoreVirtualMembers - disables generation of members marked as `virtual`; by default set to `false`\n\n#### Example\n\n```csharp\n[Theory]\n[AutoMockData]\npublic void GivenCurrencyConverter_WhenConvertToPln_ThenMustReturnCorrectConvertedAmount(\n    string testCurrencySymbol,\n    [Frozen] ICurrencyExchangeProvider currencyProvider,\n    CurrencyConverter currencyConverter)\n{\n    // Arrange\n    Mock.Get(currencyProvider)\n        .Setup(cp =\u003e cp.GetCurrencyExchangeRate(testCurrencySymbol))\n        .Returns(100M);\n\n    // Act\n    decimal result = currencyConverter.ConvertToPln(testCurrencySymbol, 100M);\n\n    // Assert\n    Assert.Equal(10000M, result);\n}\n```\n\n### InlineAutoMockData\n\nProvides a data source for a `Theory`, with the data coming from inline values combined with auto-generated data specimens generated by [AutoFixture](https://github.com/AutoFixture/AutoFixture) with a mocking library.\n\n#### Arguments\n\n- IgnoreVirtualMembers - disables generation of members marked as `virtual`; by default set to `false`\n\n#### Example\n\n```csharp\n[Theory]\n[InlineAutoMockData(\"USD\", 3, 10, 30)]\n[InlineAutoMockData(\"EUR\", 4, 20, 80)]\npublic void GivenCurrencyConverter_WhenConvertToPln_ThenMustReturnCorrectConvertedAmount(\n    string testCurrencySymbol,\n    decimal exchangeRate,\n    decimal currencyAmount,\n    decimal expectedPlnAmount,\n    [Frozen] ICurrencyExchangeProvider currencyProvider,\n    CurrencyConverter currencyConverter)\n{\n    // Arrange\n    Mock.Get(currencyProvider)\n        .Setup(cp =\u003e cp.GetCurrencyExchangeRate(testCurrencySymbol))\n        .Returns(exchangeRate);\n\n    // Act\n    decimal result = currencyConverter.ConvertToPln(testCurrencySymbol, currencyAmount);\n\n    // Assert\n    Assert.Equal(expectedPlnAmount, result);\n}\n```\n\n### MemberAutoMockData\n\nProvides a data source for a `Theory`, with the data coming from one of the following sources:\n\n- A static property\n- A static field\n- A static method (with parameters)\n\ncombined with auto-generated data specimens generated by [AutoFixture](https://github.com/AutoFixture/AutoFixture) with a mocking library.\n\nThe member must return something compatible with `Enumerable\u003cobject[]\u003e` with the test data.\n\n**Caution:** The property is completely enumerated by .ToList() before any test is run. Hence it should return independent object sets.\n\n#### Arguments\n\n- IgnoreVirtualMembers - disables generation of members marked as `virtual`; by default set to `false`\n- ShareFixture - indicates whether to share a `fixture` across all data items should be used or new one; by default set to `true`\n\n#### Example\n\n```csharp\npublic class CurrencyConverterFixture\n{\n    public static IEnumerable\u003cobject[]\u003e CurrencyConversionRatesWithResult()\n    {\n        return new List\u003cobject[]\u003e\n            {\n                new object[] { \"USD\", 3M, 10M, 30M },\n                new object[] { \"EUR\", 4M, 20M, 80M }\n            };\n    }\n}\n```\n\n```csharp\n[Theory]\n[MemberAutoMockData(\"CurrencyConversionRatesWithResult\", MemberType = typeof(CurrencyConverterFixture))]\npublic void GivenCurrencyConverter_WhenConvertToPln_ThenMustReturnCorrectConvertedAmount(\n    string testCurrencySymbol,\n    decimal exchangeRate,\n    decimal currencyAmount,\n    decimal expectedPlnAmount,\n    [Frozen] ICurrencyExchangeProvider currencyProvider,\n    CurrencyConverter currencyConverter)\n{\n    // Arrange\n    Mock.Get(currencyProvider)\n        .Setup(cp =\u003e cp.GetCurrencyExchangeRate(testCurrencySymbol))\n        .Returns(exchangeRate);\n\n    // Act\n    decimal result = currencyConverter.ConvertToPln(testCurrencySymbol, currencyAmount);\n\n    // Assert\n    Assert.Equal(expectedPlnAmount, result);\n}\n```\n\n### IgnoreVirtualMembers\n\nAn attribute that can be applied to parameters in an `AutoDataAttribute`-driven `Theory` to indicate that the parameter value should not have `virtual` properties populated when the `IFixture` creates an instance of that type.\n\nThis attribute allows to disable the generation of members marked as `virtual` on a decorated type wheres `IgnoreVirtualMembers` arguments of mocking attributes mentioned above disable such a generation for all types created by `IFixture`.\n\n**Caution:** Order is important! Applying `IgnoreVirtualMembers` attribute to the subsequent parameter makes preceding parameters of the same type to have `virtual` properties populated and the particular parameter with the following ones of the same type to have `virtual` properties unpopulated.\n\n#### Example\n\n```csharp\npublic class User\n{\n    public string Name { get; set; }\n    public virtual Address Address { get; set; }\n}\n```\n\n```csharp\n[Theory]\n[AutoData]\npublic void IgnoreVirtualMembersUsage(\n    User firstUser,\n    [IgnoreVirtualMembers] User secondUser,\n    User thirdUser)\n{\n    Assert.NotNull(firstUser.Name);\n    Assert.NotNull(firstUser.Address);\n\n    Assert.NotNull(secondUser.Name);\n    Assert.Null(secondUser.Address);\n\n    Assert.NotNull(thirdUser.Name);\n    Assert.Null(thirdUser.Address);\n}\n```\n\n### CustomizeWith *(borrowed from [@devdigital](https://github.com/devdigital/practice-guide-dotnet-testing/wiki/Unit-Tests-Implementation))*\n\nAn attribute that can be applied to parameters in an `AutoDataAttribute`-driven `Theory` to apply additional customization when the `IFixture` creates an instance of that type.\n\n#### Arguments\n\n- IncludeParameterType - indicates whether attribute target parameter `Type` should included as a first argument when creating customization; by default set to `false`\n\n**Caution:** Order is important! Applying `CustomizeWith` attribute to the subsequent parameter makes preceding parameters of the same type to be created without specified customization and the particular parameter with the specified customization.\n\n#### Example\n\n```csharp\npublic class LocalDatesCustomization : ICustomization\n{\n    public void Customize(IFixture fixture)\n    {\n        fixture.Register(() =\u003e LocalDate.FromDateTime(fixture.Create\u003cDateTime\u003e()));\n    }\n}\n```\n\n```csharp\n[Theory]\n[InlineAutoMockData(\"USD\")]\n[InlineAutoMockData(\"EUR\")]\npublic void GivenCurrencyConverter_WhenConvertToPlnAtParticularDay_ThenMustReturnCorrectConvertedAmount(\n    string testCurrencySymbol,\n    [CustomizeWith(typeof(LocalDatesCustomization))] LocalDate day,\n    [Frozen] ICurrencyExchangeProvider currencyProvider,\n    CurrencyConverter currencyConverter)\n{\n    // Arrange\n    Mock.Get(currencyProvider)\n        .Setup(cp =\u003e cp.GetCurrencyExchangeRate(testCurrencySymbol, day))\n        .Returns(100M);\n\n    // Act\n    decimal result = currencyConverter.ConvertToPln(testCurrencySymbol, 100M, day);\n\n    // Assert\n    Assert.Equal(10000M, result);\n}\n```\n\n### CustomizeWith\\\u003cT\u003e\n\nA generic version of the `CustomizeWith` attribute has been introduced for ease of use. The same rules apply as for the non-generic version.\n\n#### Example\n\n```csharp\npublic class EmptyCollectionCustomization : ICustomization\n{\n    public EmptyCollectionCustomization(Type reflectedType)\n    {\n        this.ReflectedType = reflectedType;\n    }\n\n    public Type ReflectedType { get; }\n\n    public void Customize(IFixture fixture)\n    {\n        var emptyArray = Array.CreateInstance(this.ReflectedType.GenericTypeArguments.Single(), 0);\n\n        fixture.Customizations.Add(\n            new FilteringSpecimenBuilder(\n                new FixedBuilder(emptyArray),\n                new ExactTypeSpecification(this.ReflectedType)));\n    }\n}\n```\n\n```csharp\npublic sealed class EmptyCollectionAttribute : CustomizeWithAttribute\u003cEmptyCollectionCustomization\u003e\n{\n    public EmptyCollectionAttribute()\n    {\n        this.IncludeParameterType = true;\n    }\n}\n```\n\n```csharp\n[Theory]\n[AutoData]\npublic void CustomizeWithAttributeUsage(\n    IList\u003cstring\u003e firstStore,\n    [EmptyCollection] IList\u003cstring\u003e secondStore,\n    IList\u003cstring\u003e thirdStore,\n    IList\u003cint?\u003e fourthStore)\n{\n    Assert.NotEmpty(firstStore);\n    Assert.Empty(secondStore);\n    Assert.Empty(thirdStore);\n    Assert.NotEmpty(fourthStore);\n}\n```\n\n***\n\n## Data filtering attributes\n\nThe following attributes helps narrowing down data generation to specific values or omitting certain values.\n\nFor these attributes to work, they must be used in conjunction with other data generation attributes.\n\nThey can be applied to simple types and collections.\n\n### Except\n\nAn attribute ensuring that values from outside the specified list will be generated.\n\n#### Example\n\n```csharp\n[Theory]\n[AutoData]\npublic void ExceptAttributeUsage(\n    [Except(DayOfWeek.Saturday, DayOfWeek.Sunday)] DayOfWeek workday)\n{\n    Assert.True(workday is \u003e= DayOfWeek.Monday and \u003c= DayOfWeek.Friday);\n}\n```\n\n### PickFromRange\n\nAn attribute ensuring that only values from specified range will be generated.\n\n#### Example\n\n```csharp\n[Theory]\n[AutoData]\npublic void RangeAttributeUsage(\n    [PickFromRange(11, 19)] int teenagerAge)\n{\n    Assert.True(teenagerAge is \u003e 11 and \u003c 19);\n}\n```\n\n### PickNegative\n\nAn attribute ensuring that only negative values will be generated.\n\n**Caution:** It will throw exception when being used on unsupported type or on the one which does not accept negative values.\n\n#### Example\n\n```csharp\n[Theory]\n[AutoData]\npublic void NegativeAttributeUsage(\n    [PickNegative] int negativeNumber)\n{\n    Assert.True(negativeNumber \u003c 0);\n}\n```\n\n### PickFromValues\n\nAn attribute ensuring that only values from the specified list will be generated.\n\n#### Example\n\n```csharp\n[Theory]\n[AutoData]\npublic void ValuesAttributeUsage(\n    [PickFromValues(DayOfWeek.Saturday, DayOfWeek.Sunday)] HashSet\u003cDayOfWeek\u003e weekend)\n{\n    var weekendDays = new[] { DayOfWeek.Saturday, DayOfWeek.Sunday };\n    Assert.Equivalent(weekendDays, weekend);\n}\n```\n\n***\n\n## Tips and tricks\n\n### Fixture injection\n\nYou can inject same instance of `IFixture` to a test method by adding mentioned interface as an argument of test method.\n\n```csharp\n[Theory]\n[AutoMockData]\npublic void FixtureInjection(IFixture fixture)\n{\n    Assert.NotNull(fixture);\n}\n```\n\n### IgnoreVirtualMembers issue\n\nYou should be aware that the *CLR* requires that interface methods be marked as virtual. Please look at the following example:\n\n```csharp\npublic interface IUser\n{\n    string Name { get; set; }\n    User Substitute { get; set; }\n}\n\npublic class User : IUser\n{\n    public string Name { get; set; }\n    public virtual User Substitute { get; set; }\n}\n```\n\nYou can see than only `Substitute` property has been explicitly marked as `virtual`. In such situation *the compiler* will mark other properties as `virtual` and `sealed`. And finally [AutoFixture](https://github.com/AutoFixture/AutoFixture) will assign `null` value to those properties when option `IgnoreVirtualMembers` will be set to `true`.\n\n```csharp\n[Theory]\n[AutoMockData(IgnoreVirtualMembers = true)]\npublic void IssueWithClassThatImplementsInterface(User user)\n{\n    Assert.Null(user.Name);\n    Assert.Null(user.Substitute);\n}\n```\n\n## Badges\n\n| License                                           | Code Coverage Map |\n| :---------------------------------------------------------|:--------------------------- |\n| [![FOSSA Status](https://app.fossa.com/api/projects/git%2Bgithub.com%2FObjectivityLtd%2FAutoFixture.XUnit2.AutoMock.svg?type=large)](https://app.fossa.com/projects/git%2Bgithub.com%2FObjectivityLtd%2FAutoFixture.XUnit2.AutoMock?ref=badge_large) | [![Code Coverage Map](https://codecov.io/gh/Accenture/AutoFixture.XUnit2.AutoMock/graphs/sunburst.svg?token=OuraRI8NpJ)](https://codecov.io/gh/Accenture/AutoFixture.XUnit2.AutoMock) |\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Faccenture%2Fautofixture.xunit2.automock","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Faccenture%2Fautofixture.xunit2.automock","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Faccenture%2Fautofixture.xunit2.automock/lists"}