Moq返回零结果

时间:2018-12-25 15:50:52

标签: c# entity-framework moq

我正在尝试使用Moq来测试EntityFramework代码,并且为什么在设置后它会返回零结果。

试图在workerController上创建无参数构造函数-返回相同的零项

public class WorkerDbTest
{
    private readonly Mock<IWorkerReprisatory> _repo;
    private readonly WorkersController _controller;
    private readonly List<Worker> workers;
    public WorkerDbTest()
    {
        _logger = new Mock<ILogger<WorkersController>>();
        workers = new List<Worker>
        {
            new Worker() {
                Id = 0,
                FirstName = "John",
                MiddleName = "Abraham",
                LastName = "Doe",
                Workplace = "Bomj",
                BirthDate = new DateTime(1700,10,10),
                Employed = new DateTime(1800,10,10)},
            new Worker() {
                Id = 1,
                FirstName = "Alaster",
                MiddleName = "Crowly",
                LastName = "Johns",
                Workplace = "VipBomj",
                BirthDate = new DateTime(1800,12,12),
                Employed = new DateTime(1900,12,12)},
            new Worker() {
                Id = 2,
                FirstName = "Jane",
                MiddleName = "Susan",
                LastName = "Black",
                Workplace = "FemenistBobj",
                BirthDate = new DateTime(2000,11,11),
                Employed = new DateTime(2010,11,11)}
        };
        IQueryable<Worker> workersq = workers.AsQueryable();
        _repo = new Mock<IWorkerReprisatory>();
        _repo.Setup(x => x.GetAll(new WorkerQueryParameters())).Returns(workersq);
    }

    [Fact]
    public void GetOkResult()
    {
        var tst = _repo.Object.GetAll(new WorkerQueryParameters());
    }
}

//Controller class GetAllWorkers
public IActionResult GetAllWorkers(WorkerQueryParameters workerQueryParameters)
    {
        //_logger.LogInformation("GetAllCustomersStarted");
        var allWorkers = _workerRepository.GetAll(workerQueryParameters).ToList();
        var allWorkersDTO = allWorkers.Select(x => Mapper.Map<WorkerDTO>(x));
        if(Response != null)
        {
            Response.Headers.Add("X-Pagination",
            JsonConvert.SerializeObject(new { totalCount = _workerRepository.Count() }));
        }
        return Ok(allWorkersDTO);
    }

当前,allWorkers对象在调用后结果为0。 所以我想测试一下是否有来自Mock对象的任何结果,然后得到var tst,仍然没有条目(

假设GetAll()应该返回我在那儿添加的三个人作为iQueryables

2 个答案:

答案 0 :(得分:0)

您的设置方法与实际的对象引用WorkerQueryParameters匹配,您将需要使用相同的对象引用,或者,您需要将给定值与It.Is<WorkerQueryParameters>(x => x.Value == true)匹配,或者仅匹配任何It.Any<WorkerQueryParameters>(),例如:

    _repo.Setup(x => x.GetAll(It.Any<WorkerQueryParameters>())).Returns(workersq);

也许还应该将您的模拟设置为醒目,以便抛出而不是仅返回null或默认值。

    _repo = new Mock<IWorkerReprisatory>(MockBehavior.Strict);

答案 1 :(得分:0)

为什么要在启动时添加一个参数并使用它代替New WorkerQueryParams()来解决问题。我仍然不知道为什么,但是它工作得很好,并返回3个条目。 感谢所有参与其中的人和@Nikosi的想法)

d = dict()
for i in your_list:
    d[i[0]] = set(d[i[0]]).union(set(i[1:]))