开发者

How to Moq a Method that Have parameters and have to do something with a list

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(task开发者_如何学Pythons.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.


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.


I believe you're looking for the Callback method:

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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜