1

Hi is it possible to moq something like this. I'm using the MVC pattern and I'm testing my Controller Layer. I have already tested the method getListForId in my Service layer so I can trust that it will return the correct value.

public List<object> getListForID(int id)

And I use it like this

if(true)
{
    getListForID(1).Where(a => a.Id == objectB.Id)
}
else
{
    getListForID(1)
}

The code testing each path would be the same even tho there is a where in the true path.

Is it possible to verify that the method was called with the where clause ? And is there any value in doing this?

4

1 回答 1

3

您应该测试一种行为,而不是实现。如果您已经测试了服务层,那么对于您的控制器测试,您应该模拟服务层,并getById返回一个具有可能值的对象列表,然后测试该列表是否被正确过滤:

(伪代码如下)

// arrange
var serviceOutput = new List<MyEntity>
{
   new MyEntity{Id = 1},
   new MyEntity{Id = 2}
}
var mockService = new Mock<IMyService>();
mockService.Setup(s=>s.GetById(1)).Returns(serviceOutput);

var lookupObject = new MyEntity{Id = 1};

var testController = new MyController(mockService.Object);

// act
var result = controller.FindSimilar(lookupObject);

// assert
result.Should().Have.Count().EqualTo(1);
result[0].Should().Be.SameInstanceAs(serviceOutput[0]);
于 2013-08-06T14:10:01.260 回答