mvc4 mock设置等待操作

时间:2015-08-11 12:53:55

标签: c# mongodb asp.net-mvc-4 mocking

我设置了工作模式单元以及存储库模式,我正在使用mongodb。

public class CourseRepository : ICourseRepository
{
    private IMongoCollection<Course> _dbContext = null;
    public CourseRepository(IMongoCollection<Course> dbContext)
    {
        _dbContext = dbContext;
    }
    public async Task Add(Course entity)
    {
        await _dbContext.InsertOneAsync(entity);
    }
}

在使用moq编写单元测试用例时,我编写了代码

[TestMethod]
public async Task TestMethod2()
{
       var c = new Mock<ICourseRepository>();
       c.Setup(x => x.Add(new Course { CourseName = "asfd", CourseId = 2, CourseStatus = "Active", CourseStartDate = System.DateTime.Now, CourseEndDate = System.DateTime.Now, CourseEntryDate = System.DateTime.Now })).Verifiable();
       c.Object.Add(new Course { CourseName = "asfd", CourseId = 2, CourseStatus = "Active", CourseStartDate = System.DateTime.Now, CourseEndDate = System.DateTime.Now, CourseEntryDate = System.DateTime.Now });
       c.VerifyAll();
}

我收到以下错误:

Result Message: 
Test method mvc4test.Tests.UnitTest1.TestMethod2 threw exception: 
Moq.MockVerificationException: The following setups were not matched:
ICourseRepository x => x.Add()
Result StackTrace:  
at Moq.Mock.VerifyAll()
   at mvc4test.Tests.UnitTest1.<TestMethod2>d__b.MoveNext() in c:\Users\RM250443\Documents\Visual Studio 2013\Projects\mvc4test\mvc4test.Tests\UnitTest1.cs:line 37
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter.GetResult()

任何人都可以帮助我如何测试一个异步,任务和等待的方法。

1 个答案:

答案 0 :(得分:0)

经过R&amp; D的批发后,我发现我在设置中使用了两个课程实体一个实例,而在调用方法时使用了一个实例,但应该这样做:

[TestMethod]
        public async Task TestMethod2()
        {
            var c = new Mock<ICourseRepository>();
            Course a = new Course { CourseId = 1 };
            c.Setup(x => x.Add(a)).Verifiable();
            c.Object.Add(a);
            c.VerifyAll();
        }