Skip to content

Instantly share code, notes, and snippets.

@skalinets
Last active February 29, 2024 02:46
Show Gist options
  • Star 5 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save skalinets/4571557 to your computer and use it in GitHub Desktop.
Save skalinets/4571557 to your computer and use it in GitHub Desktop.
AutoFixture + NSubstitute Demo
using NSubstitute;
using Ploeh.AutoFixture;
using Ploeh.AutoFixture.AutoNSubstitute;
using Ploeh.AutoFixture.Xunit;
using Xunit.Extensions;
namespace AutofixtureDemo
{
public class AutoNSubstituteDemo
{
[Theory, AutoNSubstituteData]
public void should_validate_password_and_record(
User user,
[Frozen] IValidator validator,
[Frozen] IAuditLogger auditLogger,
Controller controller)
{
// arrange
validator.IsValidPassword(user.Password).Returns(true);
// act
controller.RegisterUser(user);
// assert
auditLogger.Received().Log("password is ok, user: " + user.Name);
}
}
public class AutoNSubstituteDataAttribute : AutoDataAttribute
{
public AutoNSubstituteDataAttribute()
: base(() => new Fixture()
.Customize(new AutoNSubstituteCustomization()))
{
}
}
public class User
{
public string Name { get; set; }
public string Password { get; set; }
}
public interface IAuditLogger
{
void Log(string message);
}
public class Controller
{
private readonly IValidator validator;
private readonly IAuditLogger auditLogger;
public Controller(IValidator validator, IAuditLogger auditLogger)
{
this.validator = validator;
this.auditLogger = auditLogger;
}
public void RegisterUser(User user)
{
if (validator.IsValidPassword(user.Password))
{
auditLogger.Log("password is ok, user: " + user.Name);
}
}
}
public interface IValidator
{
bool IsValidPassword(string password);
}
}
@mattiasnordqvist
Copy link

The used AutoDataAttribute-constructor is now deprecated

@Layarion
Copy link

The used AutoDataAttribute-constructor is now deprecated

I'm stupid and new to programming, so then what do I do instead if I want to use these two things together?

@mattiasnordqvist
Copy link

Generally, you find a new way, because this old way of doing it is going out of support.

In this specific case, this seems to do the trick:

public class AutoNSubstituteDataAttribute : AutoDataAttribute
    {
        public AutoNSubstituteDataAttribute()
            : base(() => new Fixture()
            .Customize(new AutoNSubstituteCustomization()))
        {
        }
    }

@skalinets
Copy link
Author

@mattiasnordqvist exactly. Sorry -- didn't get to this thread at time. This is the code I have been using since they changed the API. I will update the gist, thatnks.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment