Mvc4模拟设置等待操作

本文关键字:操作 等待 设置 模拟 Mvc4 | 更新日期: 2023-09-27 18:07:30

我已经设置了工作模式单元以及存储库模式,我在其中使用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()

有没有人可以帮助我如何测试一个方法,包括异步,任务随着等待。

Mvc4模拟设置等待操作

经过大量的研究,我发现我使用了两个实例,当然实体一个在设置中,一个在调用方法时,但它应该这样做:

[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();
        }