I have a Apicontroller Which has dependency on unit of work object. How to write a test case for mocking ApiController Which has dependency on unit of work implemented in ApiController constructor.

Here is the code:

ApiController:

public class UserController : ApiController
{
    public IUoW UoW { get; set; }
    // GET api/user
    public UserController(IUoW uow)
    {
        UoW = uow;
    }

    public IEnumerable<Users> Get()
    {
        return UoW.Users.Getall();
    }     
}

The Test case :

[TestMethod]
public void TestApiController()
{
    var userManager = new Mock<IUoW>();
    userManager.Setup(s => s.Users);

    var controller = new UserController(userManager.Object);
    var values = controller.Get();
    Assert.IsNotNull(values);
}

The Users Class which has been mentioned here in UoW.Users is

public class UoW:IUoW,IDisposable
{
    private MvcWebApiContext DbContext { get; set; }
    protected IRepositoryProvider RepositoryProvider { get; set; }

    private IRepository<T> GetStandardRepo<T>() where T : class
    {
        return RepositoryProvider.GetRepositoryForEntityType<T>();
    }

    public IRepository<Users> Users
    {
        get { return GetStandardRepo<Users>(); }
    }
}

and the Users class itself is

[Table("UserProfile")]
public class Users
{
    [Key]
    [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
    public int UserId { get; set; }


    public string FirstName { get; set; }
    public string LastName { get; set; }
    public string UserName { get; set; }
    public string Password { get; set; }

    [DataType(DataType.PhoneNumber)]
    public long Mobile { get; set; }
}

When I am trying to debug the test case , the Test case shows the object UoW.Users is null in UserController. Its obvious its not initializing through WebActivator since global.asax isnt invoked here through mock. Now how to write a successful test scenario in this context so that the WebApicontroller returns me the users object with data ?

有帮助吗?

解决方案

Are you using Moq?

As I cannot see what type the UoW.Users property is I cannot demo how to mock it properly (updated IRepository) but that should be mocked and the GetAll method stubbed to return a sample list of users.

Updated

        var userManager = new Mock<IUoW>();

        userManager.Setup(s => s.Users).Returns(()=> 
        { 
            var userReposisitory = new Mock<IRepository<Users>>();

            userReposisitory.Setup(ur => ur.GetAll()).Returns(()=> {
                var listOfUsers = new List<Users>();
                listOfUsers.Add(new Users { FirstName = "Example" });
                return listOfUsers.AsQueryable();
            });

            return userReposisitory.Object; 
        });

        var controller = new UserController(userManager.Object);
        var result = controller.Get();
        Assert.IsNotNull(result);
        Assert.IsTrue(result.Count() > 0);
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top