views:

52

answers:

2

I have set a test using Moq 3.0. I need to test a method that will change some value in that database. I am using ASP.NET MVC so I want to test my controller.

I setup this

 // Generate an implementer of IProductsRepository at runtime using Moq
 var mockTareasRepos = new Mock<IRepository>();
 mockTareasRepos.Setup(x => x.ExecutedTask).Returns(tasks.AsQueryable());
 return mockTareasRepos.Object;

I need to add a new method that get a taskId and change the value of a field in a list of tasks. Suppose that the value I need to change is StartTime that is a datetime, I need to set the value to null and I need to set that retrys value plus one.

this is the task Class

public class {
     int taskId {get;set;}
     DateTime StartTime  {get;set;}
     int retrys {get;set;}
}

How I do that?

 mockTareasRepos.Setup(x => x.SetToExecuteTask(It.IsAny<int>()))

I hope you understand what I need, My English is not so good.

+1  A: 

If I understood it correcly, you want to test that after calling your Controller's method, your database value should be updated. Your mocking your repository because you don't want to setup a test database, right? So, your test should be something like this:

mockTareasRepos.Setup(...) //Do the setup you need.
var controller = new YourController(mockTareasRepos);
controller.YourMethod();
mockTareasRepos.Verify(x => x.YourRepositoryUpdateMethod(It.IsAny<Task>, Times.Once())); 

The last line will verify if your controller called the 'YourRepositoryUpdateMethod' method once. By doing this, your testing that your controller method calls the Repository interface to update your database.

I hope it helps. If this is not what your looking for, please, give us more information.

Guilherme Oenning
It helps but I still need to execute some king of method so I can have for example a object remove form the list - like if its remove form the database - because my controller should give me the value of Coutn of the list.
Jedi Master Spooky
What is the responsability of your CONTROLLER? Test that, not your repository, that's why your mocking it. You don't need to test if your repository is removing something from a list because that is the resposability of the repository, not the Controller's (which is the System Under Test).
Guilherme Oenning
+1  A: 

I believe you're looking for the Callback method:

mockTareasRepos.Setup(x => x.RepositoryMethod(...))
    .Callback<IEnumerable<Task>>(tasks => /* modify tasks here */);
    .Returns(tasks.AsQueryable());
arootbeer