NSubstitute:模拟REST API,根据参数值返回结果

时间:2018-10-24 10:27:30

标签: mocking servicestack nsubstitute

我正在使用NSubstitute模拟返回雇员对象的servicestack REST API的结果

var mockedCoreService = Substitute.For<jsonClient>(ApiUrl); 

//Create the employee to return for mocking
var employee = new EmployeeDTO { SSN = "123695874"};

// Get the mocked employee whenver GetEmployee API call is made
mockedCoreService.Get(Arg.Any<GetEmployee>()).Returns(employee);

Getemployee API调用接受Id作为参数,我想根据发送的Id返回不同的员工。

//check the id parameter of GetEmployee and return employee based on the condition in below statement  
    mockedCoreService.Get(Arg.Any<GetEmployee>()).Returns(employee);

我不确定该怎么做。请帮忙。

谢谢, 阿莫尔

2 个答案:

答案 0 :(得分:1)

自己找到答案

 mockedCoreService.Get(Arg.Is<GetEmployee>(x=>x.id == 1)).Returns(employee);

 mockedCoreService.Get(Arg.Is<GetEmployee>(x => x.id== 2)).Returns(employee2);

答案 1 :(得分:0)

另一种方法可以“动态”创建返回的实例。 Returns提供了接受方法的重载方法,该函数将返回期望值。
因此,您可以根据接收到的参数生成返回值。

fakeService.Get(null)
           .ReturnForAnyArgs(call => new Employee { Id = call.Arg<GetEmployee>().Id });