Git Product home page Git Product logo

autofixture / autofixture Goto Github PK

View Code? Open in Web Editor NEW
3.2K 93.0 336.0 102.58 MB

AutoFixture is an open source library for .NET designed to minimize the 'Arrange' phase of your unit tests in order to maximize maintainability. Its primary goal is to allow developers to focus on what is being tested rather than how to setup the test scenario, by making it easier to create object graphs containing test data.

License: MIT License

C# 98.88% F# 1.09% Batchfile 0.02% Puppet 0.01%
assertion-library assertions auto-mocking autofixture dotnet fakeiteasy fscheck moq nsubstitute nunit

autofixture's Introduction

AutoFixture

License Build status release NuGet version NuGet preview version AutoFixture

Write maintainable unit tests, faster.

AutoFixture makes it easier for developers to do Test-Driven Development by automating non-relevant Test Fixture Setup, allowing the Test Developer to focus on the essentials of each test case.

Check the testimonials to see what other people have to say about AutoFixture.

Table of Contents

Overview

(Jump straight to the CheatSheet if you just want to see some code samples right away.)

AutoFixture is designed to make Test-Driven Development more productive and unit tests more refactoring-safe. It does so by removing the need for hand-coding anonymous variables as part of a test's Fixture Setup phase. Among other features, it offers a generic implementation of the Test Data Builder pattern.

When writing unit tests, you typically need to create some objects that represent the initial state of the test. Often, an API will force you to specify much more data than you really care about, so you frequently end up creating objects that has no influence on the test, simply to make the code compile.

AutoFixture can help by creating such Anonymous Variables for you. Here's a simple example:

[Fact]
public void IntroductoryTest()
{
    // Arrange
    Fixture fixture = new Fixture();

    int expectedNumber = fixture.Create<int>();
    MyClass sut = fixture.Create<MyClass>();
    // Act
    int result = sut.Echo(expectedNumber);
    // Assert
    Assert.Equal(expectedNumber, result);
}

This example illustrates the basic principle of AutoFixture: It can create values of virtually any type without the need for you to explicitly define which values should be used. The number expectedNumber is created by a call to Create<T> - this will create a 'nice', regular integer value, saving you the effort of explicitly coming up with one.

The example also illustrates how AutoFixture can be used as a SUT Factory that creates the actual System Under Test (the MyClass instance).

Given the right combination of unit testing framework and extensions for AutoFixture, we can further reduce the above test to be even more declarative:

[Theory, AutoData]
public void IntroductoryTest(int expectedNumber, MyClass sut)
{
    int result = sut.Echo(expectedNumber);
    Assert.Equal(expectedNumber, result);
}
[Test, AutoData]
public void IntroductoryTest(int expectedNumber, MyClass sut)
{
    int result = sut.Echo(expectedNumber);
    Assert.Equal(expectedNumber, result);
}

Notice how we can reduce unit tests to state only the relevant parts of the test. The rest (variables, Fixture object) is relegated to attributes and parameter values that are supplied automatically by AutoFixture. The test is now only two lines of code.

Using AutoFixture is as easy as referencing the library and creating a new instance of the Fixture class!

Downloads

AutoFixture packages are distributed via NuGet.
To install the packages you can use the integrated package manager of your IDE, the .NET CLI, or reference the package directly in your project file.

dotnet add package AutoFixture --version 4.18.0
<PackageReference Include="AutoFixture" Version="4.18.0" />

AutoFixture offers a variety of utility packages and integrations with most of the major mocking libraries and testing frameworks.

Core packages

The core packages offer the full set of AutoFixture's features without requring any testing framework or third party integration.

Product Package Stable Preview Downloads
The core package AutoFixture NuGet NuGet NuGet
Assertion idioms AutoFixture.Idioms NuGet NuGet NuGet
Seed extensions AutoFixture.SeedExtensions NuGet NuGet NuGet

Mocking libraries

AutoFixture offers integations with most major .NET mocking libraries.
These integrations enable such features as configuring mocks, auto-injecting mocks, etc.

Product Package Stable Preview Downloads
Moq AutoFixture.AutoMoq NuGet NuGet NuGet
NSubstitute AutoFixture.AutoNSubstitute NuGet NuGet NuGet
FakeItEasy AutoFixture.AutoFakeItEasy NuGet NuGet NuGet
Rhino Mocks AutoFixture.AutoRhinoMocks NuGet NuGet NuGet

NOTE: Since AutoFixture tries maintain compatibility with a large number of package versions, the packages bundled with AutoFixture might not contain the latest features of your mocking library.
Make sure to install the latest version of the mocking library package, alongside the AutoFixture package.

Testing frameworks

AutoFixture offers integrations with most major .NET testing frameworks.
These integrations enable auto-generation of test cases, combining auto-generated data with inline arguments, etc.

Product Package Stable Preview Downloads
xUnit v2 AutoFixture.Xunit2 NuGet NuGet NuGet
NUnit v3 AutoFixture.NUnit3 NuGet NuGet NuGet
xUnit v1 AutoFixture.Xunit NuGet NuGet NuGet
NUnit v2 AutoFixture.NUnit2 NuGet NuGet NuGet
Foq AutoFixture.AutoFoq NuGet NuGet NuGet

You can check the compatibility with your target framework version on the wiki or on the NuGet website.

vNext feed

The artifacts of the next major version are published to nuget.org, and are marked with the preview suffix (e.g. 5.0.0-preview00007).
You can use these packages to early access and test the next major version of the AutoFixture.
Make sure to enable the preview packages in your IDE in order to see the latest version.

NOTE: This preview versions exists for the preview purpose only, so use them with caution:

  • New versions of packages might contain breaking changes and API could change drastically from package to package. By other words, we don't follow the SemVer policy for the packages in this feed;
  • Preview packages might be unlisted over time, in order to not clutter the version suggestion dialog in IDEs, but will generally remain available

Documentation

Additional resources

Feedback & Questions

If you have questions, feel free to ask. The best places to ask are:

License

AutoFixture is Open Source software and is released under the MIT license.
The licenses allows the use of AutoFixture libraries in free and commercial applications and libraries without restrictions.

.NET Foundation

This project is supported by the .NET Foundation.

autofixture's People

Contributors

adamchester avatar aivascu avatar alexfoxgill avatar blairconrad avatar cloggins-pcty avatar dcastro avatar dlongest avatar ecampidoglio avatar erikschierboom avatar gertjvr avatar hackle avatar holstebroe avatar jwchung avatar markwoodhall avatar micheleissa avatar moodmosaic avatar mrinaldi avatar olegsych avatar peter-raven avatar ploeh avatar pvlerick avatar sbv-csis avatar sean-gilliam avatar seanfarrow avatar sgryt avatar sshushliapin avatar teadrivendev avatar tiesmaster avatar wojcikmike avatar zvirja avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

autofixture's Issues

Upgrade AutoFixture to .NET 4

This is a breaking change, so should be made as part of the AutoFixture 3.0 release - but not before.

Note that this includes changing the nuget package to deploy to 4.0 lib.

Pit of Success defaults

AutoFixture 3 should have better defaults:

  • StableFiniteSequence
  • Multiple
  • RandomNumericSequence

Also:

  • Default Uri scheme should be "http".

Fixture should be able to resolve itself.

This is a breaking change

System.OverflowException : Value was either too large or too small for a Decimal.

With a model similar like

public class Product {

    [HiddenInput(DisplayValue=false)]
    public int Id { get; set; }

    [Required(ErrorMessage = "Please enter a product name")]
    public string Name { get; set; }

    [Required(ErrorMessage = "Please enter a description")]
    [DataType(DataType.MultilineText)]
    public string Description { get; set; }

    [Required]
    [Range(0.01, double.MaxValue, ErrorMessage = "Please enter a positive price")] 
    public decimal Price { get; set; }

    [Required(ErrorMessage = "Please specify a category")]
    public string Category { get; set; }

    public string ImageName { get; set; }

    [HiddenInput(DisplayValue = false)]
    public string ImageMimeType { get; set; }
}

and in my test
_fixture = new Fixture().Customize(new MultipleCustomization());
_fixture.CreateAnonymous<'Product'>();

When the CreateAnonymous<'Product'>() code is run. I get a System.OverflowException : Value was either too large or too small for a Decimal.

Trying to workout whether it's a bug or user error.

Sorry had to add the '' in to get the generic type to show up.

CreateMany should use frozen enumerable

The following unit test failes:

    [Fact]
    public void AutoFixtureUsesFrozenEnumerableInCreateMany()
    {
        var fixture =
            new Fixture().Customize(new MultipleCustomization())
                         .Customize(new StableFiniteSequenceCustomization());
        var expected = fixture.Freeze<IEnumerable<int>>();

        var actual = fixture.CreateMany<int>();

        Assert.Equal(expected, actual);
    }

As CreateMany<T> returns an IEnumerable<T> I would have expected to get the frozen instance.
It is arguable if this is a POLA violation or not, but even if it is not, there is currently no way to freeze the result of CreateMany<T>().

Automatically invoke Add-BindingRedirect from appropriate NuGet packages

Certain AutoFixture NuGet packages only works with an additional call to Add-BindingRedirect. With the ability to run PowerShell code upon installation of a package, we should look into whether it's possible to do this automatically.

Affected packages are (I think):

  • AutoFixture.Xunit
  • AutoFixture.AutoMoq
  • AutoFixture.AutoRhinoMocks
  • AutoFixture.AutoFakeItEasy

Automatically setting the state of the SUT

Not an issue, just a question.

Just started using AutoFixture and I'm really liking it. However, as with most things, I've had a period of productivity and now I've hit a wall. I have a method that behaves differently depending on the class' current state. The method is part of a decorator class that will optionally wrap the delegated method in a transaction:

public void DoSomething()
{
    if(!this.isLoading) 
    {
        this.TransactionallyDoSomething();
    }
}

[DatabaseTransaction]
public void TransactionallyDoSomething()
{
    this.wrappedImpl.DoSomething();
}

isLoading is a private field and will stay that way, and the only way to toggle it is to call the Load() method on the class. What I thought about was something like this:

[Theory, AutoMockData]
public void TransactionalFormDoesNotWrapSelectSubFormInTransactionBeforeLoaded([Frozen] ISessionFactory sessionFactory, TransactionalForm transactionalForm)
{
    transactionalForm.SelectSubform(new object());

    Mock.Get(sessionFactory.GetCurrentSession()).Verify(s => s.BeginTransaction(), Times.Never());
}

[Theory, AutoMockData]
public void TransactionalFormWrapsSelectSubFormInTransactionAfterLoaded([Frozen] ISessionFactory sessionFactory, [Loaded] TransactionalForm transactionalForm)
{
    transactionalForm.SelectSubform(new object());

    Mock.Get(sessionFactory.GetCurrentSession()).Verify(s => s.BeginTransaction());
    Mock.Get(sessionFactory.GetCurrentSession().BeginTransaction()).Verify(t => t.Commit());
}

Notice that I've marked the TransactionalForm parameter as [Loaded] in the second example. What I wanted this to do was call the form's Load() method before passing it in to the test, so I receive the form already in the state required for this (and likely other) tests.

I'm guessing there's already a way of doing this - albeit probably not with an attribute - that I've missed somewhere.

Support deep property comparison on likeness

The following does not work:

model.AsSource()
     .OfLikeness<MyType>()
     .OmitAutoComparison
     .WithDefaultEquality(o => o.Property.SubProperty);

There will be no compile time or runtime error but the comparison will never return true.

To make it work, the following needs to be used:

model.AsSource()
     .OfLikeness<MyType>()
     .OmitAutoComparison
     .With(o => o.Property).EqualsWhen((x, y) => Equals(x.Property.SubProperty, y.Property.SubProperty));

I find that very clumsy...
What do you think?

Freeze works not as expected

I have some Fixture setup that crashes when using freeze instead of Register:

this works
Fixture = new Fixture();
Fixture.Register(() => ContractDescription.GetContract(typeof(IFoo)));
Fixture.Register(() => new EndpointAddress("net.tcp://localhost:9001"));
Fixture.Register<ContractDescription, EndpointAddress, ServiceEndpoint>(
(contract, address) => new ServiceEndpoint(contract) { Address = address });

this crashes
Fixture = new Fixture();
Fixture.Freeze(ContractDescription.GetContract(typeof(IFoo)));
Fixture.Freeze(new EndpointAddress("net.tcp://localhost:9001")); -- crashes here with targetinvocationexception
Fixture.Register<ContractDescription, EndpointAddress, ServiceEndpoint>(
(contract, address) => new ServiceEndpoint(contract) { Address = address });

I would prefer the later version, but I don't understand why it doesn't work.
Is there any explanation for that behaviour or is it a bug?

Kind regards,
Michael

Calling CreateMany() with [Range] attribute on property throws Ploeh.AutoFixture.Kernel.RangedNumberRequest

This is almost like the already closed issue #21.

I have the AutoFixture version 2.15.4 from NuGet. This is throwing an exception again.
I have a class like this.

public class MyModel
{
    [Range(1, 100)]
    public byte Number { get; set; }
}

This code throws the following exception.

IEnumerable<MyModel> one= fixture.CreateMany<MyModel>();
MyModel[] two = one.ToArray();

Error Message AutoFixture was unable to create an instance from Ploeh.AutoFixture.Kernel.RangedNumberRequest, most likely because it has no public constructor, is an abstract or non-public type.

Remove the [Range] attribute and it works fine.

Frozen enumerable not re-used

The following unit test fails:

    [Fact]
    public void AutoFixtureReusesFrozenEnumerable()
    {
        var fixture = new Fixture().Customize(new MultipleCustomization());
        var expected = fixture.Freeze<IEnumerable<int>>();

        var actual = fixture.CreateAnonymous<IEnumerable<int>>();

        Assert.Equal(expected, actual);
    }

Adding the StableFiniteSequenceCustomization() makes the unit test pass.
However, even without the StableFiniteSequenceCustomization(), the expected behavior is to get the frozen instance - why else would I freeze it?
This is a POLA violation.
Furthermore, I might want to have the instable behavior for all other enumerables. Currently it is not possible to freeze the enumerable for a specific type while leaving all others instable.

Dispose specimens created by AutoFixture in AutoDataAttribute

Mark, how would you dispose of the specimens created by AutoFixture in the context of a AutoDataAttribute?

I am currently using an implementation of BeforeAfterTestAttribute with a thread static reference of DisposableTrackingCustomization. The from AutoDataAttribute derived class registers an instance of DisposableTrackingCustomization with AutoFixture and also registers it with the BeforeAfterTestAttribute which in turn disposes it in the After method.

However, this looks a bit messy to me because of the ThreadStatic...
Do you have a better way?

Erratic test in RegularExpressionGeneratorTest

Occassionally when running all tests, I get this test failure:

Test 'Ploeh.AutoFixtureUnitTest.RegularExpressionGeneratorTest.CreateWithRegularExpressionRequestReturnsCorrectResult("(.*l")' failed:
result: Ploeh.AutoFixture.Kernel.NoSpecimen
RegularExpressionGeneratorTest.cs(62,0): at Ploeh.AutoFixtureUnitTest.RegularExpressionGeneratorTest.CreateWithRegularExpressionRequestReturnsCorrectResult(String pattern)

This looks like an Erratic Test to me...

Feature Suggestion: Provide a means to detect when a frozen object was not actually used

Just a thought: one of my favorite things about AutoFixture is low-friction refactoring. I can alter my classes' constructors at will, often not causing my existing tests to break.
However, when I remove a constructor-injected dependency, while my tests may still pass (yay!), those tests could be left with cruft -- mock setups or frozen instances that are no longer necessary (booo).
It might be nice to have a way to warn that those setups aren't needed anymore, so I can go through and remove them from my tests.

Support for value types with default constructors

AutoFixture should optionally support value types with default constructors. See this discussion for more details.

Since I believe in the GOOS paradigm, I think it's a beneficial feature that AutoFixture OOB chokes on such constructs, but we should consider elaborating on this potential issue in the error message. E.g. instead of saying

AutoFixture was unable to create an instance from Foo, most likely because it has no public constructor, is an abstract or non-public type.

we should consider adding more information - e.g.

AutoFixture was unable to create an instance from Foo, since it's a value type with no explicit, parameterized constructors. Are you attempting to create an instance of a mutable value type? If so, you should strongly consider changing the design of the value type. However, if you are unable to do so, you can add the SupportValueTypeDefaultConstructors customizations to your Fixture instance:

var fixture = new Fixture().Customize(new SupportValueTypeDefaultConstructors());

This would obviously also require us to add said SupportValueTypeDefaultConstructors customization to the AutoFixture code base.

AutoFixture.AutoFoq

Would it make sense to write a glue library or auto-mocking extension for AutoFixture using Foq?

It would be similar to AutoFixture.AutoMoq or one of the other auto-mocking extensions, but better support unit tests in F# (at least better than Moq).

Truly random numbers which may be repeated?

According to issues #2 and #7, generated numbers are always unique, and ranges increase. However, I think that in many situations this would not be optimal. For example, some particular test might have a bug with a small number, but since it is always executed after many other tests, it is never verified with that small number. Why not to add support for random variables which may be repeated? (I feel like somebody already answered this somewhere, because question is too obvious to be simply missed, but would be interested to know the motivation.)

Chars should be random

char instances are currently generated by CharSequenceGenerator, which provides a deterministic sequence of charinstances.

Consistent with other primitive types such as strings and numbers, chars should also be randomized for AutoFixture 3.0.

This is a breaking change, so should be submitted to the 3.0 branch.

RegularExpressionAttribute

When a regular epression pattern contains "\d" it throws the following exception.

SetUp : Ploeh.AutoFixture.ObjectCreationException : 
AutoFixture was unable to create an instance from 
Ploeh.AutoFixture.Kernel.RegularExpressionRequest, 
most likely because it has no public constructor, 
is an abstract or non-public type.

Example:

Throws Exception:

[RegularExpression(@"\d{5}(-\d{4})?")]
public string Zip { get; set; }

Work around

[RegularExpression(@"[0-9]{5}(-[0-4]{4})?")]
public string Zip { get; set; }

Create truly constrained non-deterministic numbers

Numbers are currently created using a strictly monotonically increasing sequence. This may be too deterministic, causing test developers to (inadvertently) take advantage of this trait, as a result creating brittle tests.

Numbers should be created according to an appropriate assumption about a proper default Equivalence Class for numbers.

For numbers (integers, decimal values and floats alike) the assumption is that a small positive integer is rarely a problem. While negative numbers or zero are frequently invalid in various APIs, positive numbers tend to be valid. Even when input can be a decimal or a float, integers (the mathematical concept, not the data type) tend to be valid too. Large numbers can sometimes cause problems for APIs, so small numbers are preferred.

That’s what originally caused me to come up with the algorithm of using a strictly monotonically increasing sequence of integers, because that was the simplest algorithm I could come up with that fit the criteria.

A better algorithm would be to pick random small (e.g. less than 256) positive integers, making sure that none are repeated, and then expand to a bigger range (e.g. less than 32767) until that one is all used up and so on. This could be a new optional ISpecimenBuilder in AutoFixture 2.x, but should be the default in AutoFixture 3.0.

Erratic test in RandomNumericSequenceGeneratorTest

Occasionally, when running all tests, I get this test error:

Test 'Ploeh.AutoFixtureUnitTest.RandomNumericSequenceGeneratorTest.CreateReturnsUniqueNumbersOnMultipleCallAsynchronously(System.Int64[])' failed:
System.NullReferenceException : Object reference not set to an instance of an object.
at System.Linq.Enumerable.d__142.MoveNext() at System.Linq.Enumerable.<DistinctIterator>d__7a1.MoveNext()
at System.Linq.Enumerable.Count[TSource](IEnumerable`1 source)
RandomNumericSequenceGeneratorTest.cs(410,0): at Ploeh.AutoFixtureUnitTest.RandomNumericSequenceGeneratorTest.CreateReturnsUniqueNumbersOnMultipleCallAsynchronously(Int64[] limits)

System.OverflowException in RangedNumberRequest(typeof(double), double, double) constructor

I have issue trying to create anonymous instance of type with following field declaration inside:
[Range(1, double.MaxValue)] public double Value { get; set; }
Running fixture.CreateAnonymous<T>() gives me exception:

System.Exception : 1,79769313486232E+308 is not a valid value for Double.
----> System.OverflowException : Value was either too large or too small for a Double.
at System.ComponentModel.BaseNumberConverter.ConvertFrom(ITypeDescriptorContext context, CultureInfo culture, Object value)
at Ploeh.AutoFixture.Kernel.RangedNumberRequest..ctor(Type operandType, Object minimum, Object maximum)
at Ploeh.AutoFixture.DataAnnotations.RangeAttributeRelay.Create(Object request, ISpecimenContext context)
at Ploeh.AutoFixture.Kernel.CompositeSpecimenBuilder.<>c__DisplayClass6.b__1(ISpecimenBuilder b)

As I understand, this issue is caused by round-trip conversion from double to string and back on double.MaxValue value.

InvalidCastException on nullable ints with RangeAttribute

RangeAttribute supports properties of type nullable int. If I create a new object with a property of type int? and validate the object, no validation errors are shown. If I try to let AutoFixture create a new instance of my type, an exception is thrown:

Invalid cast from 'System.Int32' to 'System.Nullable1[[System.Int32, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]]'. at System.Convert.DefaultToType(IConvertible value, Type targetType, IFormatProvider provider) at System.Int32.System.IConvertible.ToType(Type type, IFormatProvider provider) at System.Convert.ChangeType(Object value, Type conversionType, IFormatProvider provider) at Ploeh.AutoFixture.DataAnnotations.RangeAttributeRelay.Create(RangeAttribute rangeAttribute, Object request) at Ploeh.AutoFixture.DataAnnotations.RangeAttributeRelay.Create(Object request, ISpecimenContext context) at Ploeh.AutoFixture.Kernel.CompositeSpecimenBuilder.<>c__DisplayClass6.<Create>b__1(ISpecimenBuilder b) at System.Linq.Enumerable.WhereSelectListIterator2.MoveNext()
at System.Linq.Enumerable.WhereSelectEnumerableIterator2.MoveNext() at System.Linq.Enumerable.<DefaultIfEmptyIterator>d__a51.MoveNext()
at System.Linq.Enumerable.FirstOrDefault[TSource](IEnumerable1 source) at Ploeh.AutoFixture.Kernel.CompositeSpecimenBuilder.Create(Object request, ISpecimenContext context) at Ploeh.AutoFixture.Kernel.Postprocessor1.Create(Object request, ISpecimenContext context)
at Ploeh.AutoFixture.Kernel.CompositeSpecimenBuilder.<>c__DisplayClass6.b__1(ISpecimenBuilder b)
at System.Linq.Enumerable.WhereSelectListIterator2.MoveNext() at System.Linq.Enumerable.WhereSelectEnumerableIterator2.MoveNext()
at System.Linq.Enumerable.d__a51.MoveNext() at System.Linq.Enumerable.FirstOrDefault[TSource](IEnumerable1 source)
at Ploeh.AutoFixture.Kernel.CompositeSpecimenBuilder.Create(Object request, ISpecimenContext context)
at Ploeh.AutoFixture.Kernel.RecursionGuard.Create(Object request, ISpecimenContext context)
at Ploeh.AutoFixture.Kernel.SpecimenContext.Resolve(Object request)
at Ploeh.AutoFixture.Kernel.AutoPropertiesCommand1.Execute(T specimen, ISpecimenContext context) at Ploeh.AutoFixture.Kernel.Postprocessor1.Create(Object request, ISpecimenContext context)
at Ploeh.AutoFixture.Kernel.CompositeSpecimenBuilder.<>c__DisplayClass6.b__1(ISpecimenBuilder b)
at System.Linq.Enumerable.WhereSelectListIterator2.MoveNext() at System.Linq.Enumerable.WhereSelectEnumerableIterator2.MoveNext()
at System.Linq.Enumerable.d__a51.MoveNext() at System.Linq.Enumerable.FirstOrDefault[TSource](IEnumerable1 source)
at Ploeh.AutoFixture.Kernel.CompositeSpecimenBuilder.Create(Object request, ISpecimenContext context)
at Ploeh.AutoFixture.Kernel.RecursionGuard.Create(Object request, ISpecimenContext context)
at Ploeh.AutoFixture.Kernel.SpecimenContext.Resolve(Object request)
at Ploeh.AutoFixture.Kernel.SeedIgnoringRelay.Create(Object request, ISpecimenContext context)
at Ploeh.AutoFixture.Kernel.CompositeSpecimenBuilder.<>c__DisplayClass6.b__1(ISpecimenBuilder b)
at System.Linq.Enumerable.WhereSelectListIterator2.MoveNext() at System.Linq.Enumerable.WhereSelectEnumerableIterator2.MoveNext()
at System.Linq.Enumerable.d__a51.MoveNext() at System.Linq.Enumerable.FirstOrDefault[TSource](IEnumerable1 source)
at Ploeh.AutoFixture.Kernel.CompositeSpecimenBuilder.Create(Object request, ISpecimenContext context)
at Ploeh.AutoFixture.Kernel.Postprocessor1.Create(Object request, ISpecimenContext context) at Ploeh.AutoFixture.Kernel.CompositeSpecimenBuilder.<>c__DisplayClass6.<Create>b__1(ISpecimenBuilder b) at System.Linq.Enumerable.WhereSelectListIterator2.MoveNext()
at System.Linq.Enumerable.WhereSelectEnumerableIterator2.MoveNext() at System.Linq.Enumerable.<DefaultIfEmptyIterator>d__a51.MoveNext()
at System.Linq.Enumerable.FirstOrDefault[TSource](IEnumerable`1 source)
at Ploeh.AutoFixture.Kernel.CompositeSpecimenBuilder.Create(Object request, ISpecimenContext context)
at Ploeh.AutoFixture.Kernel.RecursionGuard.Create(Object request, ISpecimenContext context)
at Ploeh.AutoFixture.Kernel.SpecimenContext.Resolve(Object request)
at Ploeh.AutoFixture.SpecimenFactory.CreateAnonymous[T](ISpecimenContext context, T seed)
at Ploeh.AutoFixture.SpecimenFactory.CreateAnonymous[T](ISpecimenContext context)
at Ploeh.AutoFixture.SpecimenFactory.CreateAnonymous[T](ISpecimenBuilderComposer composer)
at AutoFixtureBug.Program.Main(String[] args) in c:\home\AutoFixtureBug\AutoFixtureBug\Program.cs:line 17
at System.AppDomain._nExecuteAssembly(RuntimeAssembly assembly, String[] args)
at System.AppDomain.ExecuteAssembly(String assemblyFile, Evidence assemblySecurity, String[] args)
at Microsoft.VisualStudio.HostingProcess.HostProc.RunUsersAssembly()
at System.Threading.ThreadHelper.ThreadStart_Context(Object state)
at System.Threading.ExecutionContext.RunInternal(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx)
at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx)
at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state)
at System.Threading.ThreadHelper.ThreadStart()

Erratic tests related to [Range] attribute

In the v3.0 branch I'm starting to see erratic tests related to the [Range] attribute handling. So far, I've seen this:

Test 'Ploeh.AutoFixtureUnitTest.FixtureTest.CreateAnonymousWithRangeValidatedDecimalPropertyReturnsCorrectResultForIntegerRange' failed:
    Expected result to fall into the interval [10, 20], but was 21
    FixtureTest.cs(1285,0): at Ploeh.AutoFixtureUnitTest.FixtureTest.CreateAnonymousWithRangeValidatedDecimalPropertyReturnsCorrectResultForIntegerRange()


Test 'Ploeh.AutoFixtureUnitTest.FixtureTest.CreateAnonymousWithRangeValidatedDecimalPropertyReturnsCorrectResultForIntegerRange' failed:
    Expected result to fall into the interval [10, 20], but was 24
    FixtureTest.cs(1285,0): at Ploeh.AutoFixtureUnitTest.FixtureTest.CreateAnonymousWithRangeValidatedDecimalPropertyReturnsCorrectResultForIntegerRange()

I've seen more than these, and every time I've changed the test method to output more detailed information about the values involved, but the above examples are the only one so far I've been able to capture with that increased level of detail.

Put unit tests naming convention in Wiki

AutoFixture has a very nice naming convention for its unit test methods. It can be a naming convention reference for unit test classes and methods for other projects as well.

Please describe about this convention in Wiki.

Provide StringLengthAttribute for method parameters

The StringLengthAttribute from DataAnnotations is not allowed on method parameters. However, especially in the context of integration tests written with an AutoDataAttribute derived type it would be very handy.

Example:

[Theory, AutoCoreDataData, DisposeAutoTestData]
public void SavingAnExistingItem_ShouldUpdateTheDataInTheDatabase(
    QuantityTestStoresRepository sut, [StringLength(20)] string newDescription)
{
    var itemToUpdate = GetExistingQuantityTestStore(sut);
    itemToUpdate.ShortDescription = newDescription;

    sut.SaveItem(itemToUpdate);

    var updatedItem = GetExistingQuantityTestStore(sut);
    Assert.Equal(newDescription, updatedItem.ShortDescription);
}

Without the attribute, I will get an exception when saving the item to the database as the field only allows 20 characters.

The implementation is trivial, the question is: where to put it? Should it be put into Xunit as it only seems to make sense in the unit testing scenario? However, it is in no way actually linked to xUnit. So my suggestion would be to put it into the main AutoFixture code base.

If you agree that it is useful in AutoFixture, I can implement the change.

Remove ISpecimenBuilderComposer

The ISpecimenBuilderComposer interface needs to go.

This is a breaking change, so should be done as part of the version 3 release.

WithoutType

Hi,

im trying to Autofixture some servicecontracts.

I get this
"AutoFixture was unable to create an instance from System.Runtime.Serialization.ExtensionDataObject, most likely because it has no public constructor, is an abstract or non-public type."

Would it be possible to do something like

AutoFixture.Build().WithoutType(t => t == ExtensionDataObject).CreateAnonymous();

best regards
Twd

Compose marker nodes instead of inheriting

The following marker nodes derive from CompositeSpecimenBuilder:

  • BehaviorRoot
  • CustomizationNode
  • AutoPropertiesTarget
  • ResidueCollectorNode

Instead of deriving from CompositeSpecimenBuilder, they should just Decorate any ISpecimenBuilder.

This is a breaking change, so should be made as part of the version 3 release.

Using IIdiomaticAssertion to implement assertion that Equals is implemented correctly

I am wondering whether it is correct to implement IIdiomaticAssertion if I want to encapsulate a test that verifies that Equals is implemented correctly.
I am asking, because most of the methods on that interface wouldn't really be usable in such an assertion.
If it is not the right way - is there some other infrastructure in Idioms I can reuse or should I just go ahead an write my own CorrectEqualsImplementationAssertion without implementing any existing interface?

StackOverflowException with registered abstract classes.‏

Say I have the following classes:

public abstract class ItemBase
{
    public int ItemId { get; set; }

    public ICollection<ItemLocation> Locations { get; set; }
}

public class FunkyItem : ItemBase
{
    public int Funkiness { get; set; }
}

public class ItemLocation
{
    public int LocationId { get; set; }

    public ItemBase Item { get; set; }
}

And my fixture created as follows:

var fixture = new Fixture().Customize(new MultipleCustomization());
fixture.RepeatCount = 3;
fixture.Behaviors.Clear();
fixture.Behaviors.Add(new NullRecursionBehavior());

fixture.Register<ItemBase>(() => fixture.CreateAnonymous<FunkyItem>());

Doing:

var funkyItem = fixture.CreateAnonymous<FunkyItem>();

I would expect to see a FunkyItem with Locations that themselves have null references to Item, but instead I get a StackoverflowException. Changing the behavior from NullRecursionBehavior to OmitOnRecursionBehavior produces the same result.

I can successfully create the object graph by registering ItemLocation as follows:

fixture.Register<ItemLocation>(() => fixture.Build<ItemLocation>().Without(l => l.Item).CreateAnonymous());

But now I have to have specific knowledge of which properties may cause recursion, and I would like AutoFixture to do that for me. So it seems that AutoFixture is not able to detect recursion in an object graph with a registered abstract class.

ReSharper analysis results

Please take a look and edit or leave comments. It is not a suggestion to fix those issues immediately, just discussing and prioritizing them should be enough for now.

I will provide feedback from other commercial tools later as well.

how to create object with some property not set .

Just like below:
I add 'NotSetValueAttribute' to the "Spouse" property, I want fixture do not set the value to the "Spouse" property when it create Person.

public class Person {
   [NotSetValue]
   public string  Spouse {get; set;}
   public string  Name {get; set;}
}

I read the Cheatsheet, I can disable some property just like below:

var person = fixture.Build<Person>()
    .Without(p => p.Spouse)
    .CreateAnonymous();

or fixture.Customize<Person>(ob => ob.Without(p => p.Spouse));

but I do not want to use the two way, because I do not want to write the code for each class, I want all class that its property with "NotSetValueAttribute" will not set value.

How can I to complete it?
thanks very much

Ensuring Disposable of objects created from Customizations

I am writing tests for a Web API project. I want AutoFixture to provide a pre-configured HttpConfiguration fixture to my tests and properly dispose of it when my test has executed (with either outcome).

I'm using the following code:

        [AttributeUsage( AttributeTargets.All, Inherited = false, AllowMultiple = true )]
        sealed class AutoHttpConfigurationAttribute : AutoDataAttribute
        {
            public AutoHttpConfigurationAttribute()
            {
                Fixture.Customize( new DisposableTrackingCustomization() );
                Fixture.Customize( new HttpConfigurationCustomization() );
            }

            private class HttpConfigurationCustomization : ICustomization
            {
                public void Customize( IFixture fixture )
                {
                    fixture.Register<HttpConfiguration>( CreateInitializedConfiguration );

                }

                private HttpConfiguration CreateInitializedConfiguration()
                {
                    var configuration = new HttpConfiguration();
 ...
                    return configuration;
                }
            }
        }

However, it seems that the HttpConfiguration does not get disposed properly when using the attribute with a test case like this

            [Theory, AutoHttpConfiguration]
            public void TestWithConfiguration( HttpConfiguration sut )

Am I doing something wrong? How do I achieve automatic disposal of a fixture supplied by a customization? Please mark this issue as a "question".

Deprecate types and members

AutoFixture uses Semantic Versioning, so version 3 is by definition all about breaking changes.

According to the Semantic Versioning definition, breaking changes should be advertised in advance by deprecating types that are going to change or disappear. There should be at least one minor release where types are formally deprecated.

Since we are using C#, we should use the [Obsolete] attribute for this purpose, and make sure to provide a good and fulfilling message to the user.

Candidates for deprecation:

  • Composer<T>
  • TypedBuilderComposer
  • CompositeComposer<T>

ISpecimenBuilderComposer will be removed in version 3, but due to the way it's used, it's not possible to provide a satisfactory alternative before that. The main problem is that while there are alternatives for most methods taking ISpecimenBuilderComposer to instead take ISpecimenBuilder, it's currently not possible to let Fixture implement ISpecimenBuilder because this leads to other compiler errors due to ambiguity.

IFixture should, in time, be removed, but it can be more easily deprecated in the version 3 time frame, as other alternatives are in place then.

Less scary-sounding API

Consider renaming scary-sounding method names like "CreateAnonymous" to simply "Create". The new methods should be introduced and the old methods should be deprecated before version 3.

  • CreateAnonymous -> Create

Spin SemanticComparison into a separate NuGet package

SemanticComparison is currently included in the AutoFixture NuGet package, which isn't necessary. It should be taken out of the AutoFixture package and get its own package instead.

However, this is sort of a breaking change, so should happen as part of the AutoFixture 3 release.

While the removal of SemanticComparison from the AutoFixture NuGet package is a breaking change, the addition of a SemanticComparison package isn't, so even before AutoFixture 3, this package could be created and added to the NuGet repository.

Exception when trying to create a proxy of a Likeness<T, T>

Ploeh.SemanticComparison.ProxyCreationException : The proxy of CoreData.ViewModel.CompanyViewModel could not be created using the same semantic heuristics as the default semantic comparison. In order to create proxies of types with non-parameterless constructor the values from the source constructor must be compatible to the parameters of the destination constructor.
---- System.InvalidOperationException : Sequence contains no elements
at Ploeh.SemanticComparison.Likeness`2.CreateProxy()

I am trying to create a proxy on a Likeness where destination and source type are equal. To me, the error message doesn't seem to make much sense in this scenario as the parameters can certainly be mapped - it is the same constructor.

I am trying to create the proxy like so:

return
    new CompanyViewModel(model, repositoryBase).AsSource()
                                                .OfLikeness<CompanyViewModel>()
                                                .Without(o => o.Repository)
                                                .Without(o => o.mySaveHandler)
                                                .Without(o => o.exceptionHandler)
                                                .Without(o => o.HasChanges)
                                                .CreateProxy();

StringLengthAttribute not respected/ignored

Hey,

I am trying to make autofixture respect the string length attribute as I have read it will do since version 2.4. I am using v2.16.2 (with the nsubstitute addon).

given

public class Address
{
    [DisplayName("Postcode")]
    [StringLength(9)]
    public string PostCode { get; protected set; }
}

I wrote this test

var fixture = CreateFixture();
var address = fixture.CreateAnonymous<Model.Address>();
Assert.True(address.PostCode.Length <= 9);

My assertion always fails. Postcode has values like "postcodee279e469-47fb-4166-95d4-a6a650e87535". Is there something else I need to do to make this work?

StringLengthAttribute is sourced from System.ComponentModel.DataAnnotations, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.