【发布时间】:2021-07-02 13:39:04
【问题描述】:
这是我要编写测试的方法:
public class JobStore : IJobStore
{
private readonly IMongoDbContext _context;
public JobStore(IMongoDbContext context)
{
_context = context;
}
public async Task<IJob> CreateAsync(IJob job)
{
await _context.Jobs.InsertOneAsync(job as Job);
return job;
}
}
这是我的测试:
public class JobStoreTest
{
private readonly Mock<IMongoDbContext> _moqIMongoDbContext;
private readonly JobStore _jobStore;
public JobStoreTest()
{
_moqIMongoDbContext = new Mock<IMongoDbContext>();
_jobStore = new JobStore(_moqIMongoDbContext.Object);
_moqIMongoDbContext
.Setup(_ => _.Jobs.InsertOneAsync(It.IsAny<Job>(), It.IsAny<CancellationToken>()))
.Returns((IJob x) => Task.FromResult(x));
}
[Theory]
[ClassData(typeof(JobClassesForTesting))]
public async Task CreateAsync(IJob job)
{
var result = await _jobStore.CreateAsync(job);
Assert.Equal(job,result as Job);
}
}
这是测试结果:
System.ArgumentException 无效的回调。具有 2 个参数的方法上的设置无法调用具有不同数量参数 (1) 的回调。
这里是 JobClassesForTestingClass,这是我的测试场景:
public class JobClassesForTesting : IEnumerable<object[]>
{
public IEnumerator<object[]> GetEnumerator()
{
yield return new object[]
{
new Job()
{
Payload = null,
EntityName = "EntityNameTest1",
Module = "ModuleTest1",
MetaData = new Dictionary<string, string>(),
Categories = new List<JobCategory>{new JobCategory {Name = "CategoryTest1"} },
PublishedDate = DateTime.Now
}
};
yield return new object[]
{
new Job()
{
Payload = "PayloadTest2",
EntityName = "EntityNameTest2",
Module = "ModuleTest2",
MetaData = new Dictionary<string, string>(),
Categories = new List<JobCategory>{new JobCategory {Name = "CategoryTest2"} },
PublishedDate = DateTime.Now
}
};
yield return new object[]
{
new Job()
{
Payload = "PayloadTest3",
EntityName = "EntityNameTest3",
Module = "ModuleTest3",
MetaData = new Dictionary<string, string>(),
Categories = new List<JobCategory>{new JobCategory {Name = "CategoryTest3"} },
PublishedDate = DateTime.Now
}
};
}
IEnumerator IEnumerable.GetEnumerator() => GetEnumerator();
}
我希望测试结果与我的每个 Job 对象相同,但测试结果是 System.ArgumentException
【问题讨论】:
-
如 cmets 中所述,使用的回调参数与方法定义不匹配。
标签: c# unit-testing asp.net-core xunit xunit.net