Skip to content

MoqFixture simplifies the setup of mocks for Moq-driven unit testing of classes

License

Notifications You must be signed in to change notification settings

josiah-roberts/MoqFixture

 
 

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

9 Commits
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

MoqFixture

MoqFixture exists to simplify the setup of mocks for Moq-driven unit testing of classes.

Usage

MoqFixture creates a TestObject for your fixture, and provides a Mock<TMock>() function you can use to retrieve Moq mocks for your TestObject's dependencies.

Simply have your fixture inherit from MoqFixture<TypeUnderTest>, and access the Mock<TMock>() / TestObject of the base class.

Example

Test:

[TestFixture]
//Tell MoqFixture the type you're mocking dependencies for
public class UserInfoControllerFixture : MoqFixture<UserInfoController> 
{
    [Test]
    public void ShouldReturnFoundUserInfo()
    {
        var expectedUser = new User
        {
            Username = "tom",
            FullName = "tom thumb"
        };

	//The magic bit
        Mock<IUserService>() 
		.Setup(x => x.ResolveCurrentUser())
		.Returns(expectedUser);

	//TestObject is provided within the Fixture
        UserInfoView result = TestObject.Get();

        Assert.That(result.UserName, Is.EqualTo(expectedUser.Username));
        Assert.That(result.FullName, Is.EqualTo(expectedUser.FullName));
    }
}

Implementation:

public class UserInfoController : ApiController
{
    private readonly IUserService _userService;

    //Automatically called and injected by MoqFixture
    public UserInfoController(IUserService userService)
    {
        _userService = userService;
    }

    [HttpGet]
    [Route("api/v1/userinfo")]
    public UserInfoView Get()
    {
        var curUser = _userService.ResolveCurrentUser();
        return new UserInfoView
        {
            FullName = curUser.FullName,
            UserName = curUser.Username
        };
    }
}

In this example, all fixtures testing objects with an ISomeType dependency will have a preconfigured mock.

Limitations

MoqFixture cannot mock dependencies where there is ambiguity. This includes:

  • Classes with multiple constructors
  • Classes with multiple constructor arguments of the same type

MoqFixture also inherits the limitations of Moq itself, namely:

  • It cannot mock dependencies that are sealed classes
  • It cannot mock dependencies that are not classes or interfaces
  • It cannot mock members that are not virtual

About

MoqFixture simplifies the setup of mocks for Moq-driven unit testing of classes

Resources

License

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published

Languages

  • C# 100.0%