AutoFixture.Idioms
Common Use Cases:
- Testing Constructors: Automatically generates instances of dependencies to test constructor behavior.
- Method Invocation: Verifies that methods are called with the expected parameters.
- Property Behavior: Ensures that properties behave correctly when set or retrieved.
In the example below, the
GuardClauseAssertion checks that the
constructor of MyClass properly guards against null
arguments.
using AutoFixture;
using AutoFixture.Idioms;
using Xunit;
public class MyClassTests
{
private readonly IFixture _fixture;
private readonly GuardClauseAssertion _guardClauseAssertion;
public MyClassTests()
{
_fixture = new Fixture();
_guardClauseAssertion = new GuardClauseAssertion(_fixture);
}
[Fact]
public void MyConstructor_ShouldGuardAgainstNulls()
{
_guardClauseAssertion.Verify(typeof(MyClass).GetConstructors());
}
}Method Invocation Assertion: You can use MethodCallAssertion to verify that a method is called with the expected parameters.
using AutoFixture;
using AutoFixture.Idioms;
using Moq;
using Xunit;
public class UserServiceTests
{
private readonly IFixture _fixture;
private readonly Mock<IUserRepository> _userRepositoryMock;
public UserServiceTests()
{
_fixture = new Fixture();
_userRepositoryMock = new Mock<IUserRepository>();
}
[Fact]
public void AddUser_ShouldCallRepositoryAddMethod()
{
var userService = new UserService(_userRepositoryMock.Object);
var user = _fixture.Create<User>();
userService.AddUser(user);
_userRepositoryMock.Verify(repo => repo.Add(user), Times.Once);
}
}Links: