mardi 30 décembre 2014

how to unit test controller that in turn calls repository with two parameters

At present, I am writing unit tests for my controller. Below is the structure of my code in the project.


MyController Class



public class MyController : Controller
{
private readonly MyRepository _myRepository;

public MyController()
: this(new MyRepository())
{

}

[HttpGet]
public ActionResult Index()
{
var items = _myRepository.GetAllItems();
if (items.Count() == 0)
return View("EmptyItems");
else
{
return View("List", items);
}
}
}


MyRepository Class



public class MyRepository : IDisposable, IMyRepository
{
private readonly MyDbContext _dbcontext;
private readonly ISecurityService _securityService;


public TodoListItemsRepository() : this(new MyDbContext(), new SecurityService())
{

}
public TodoListItemsRepository(MyDbContext context, ISecurityService securityService)
{
_dbcontext = context;
_securityService = securityService;
}
public IEnumerable<MyModel> GetAllItems()
{
var userid = _securityService.GetUser();
var todoList = _dbcontext.MyList.Where(e => e.UserId == userid);

return todoList;
}
//Other Methods etc...
......
}


SecurityService class



public class SecurityService : ISecurityService
{
public int GetUser()
{
return (int)Membership.GetUser().ProviderUserKey;
}
}


Here all methods inside my repository depends on GetUser method. Hence, I have initialized it inside the constructor. The repository class is initialized from the controller constructor.


My issue is - I couldn't unit the Index action unless I need to initialize dbcontext and the securityservice. Could someone please advise me if I am doing the right thing or any changes required in the structure of my code so that I can unit test my application ? I am new to MVC. So, any suggestions would be much appreciated.


Aucun commentaire:

Enregistrer un commentaire