编程语言
首页 > 编程语言> > C#-犀牛-模拟代表

C#-犀牛-模拟代表

作者:互联网

public interface IServiceInvoker
{  
    R InvokeService<T, R>(Func<T, R> invokeHandler) where T : class;
}

public class MediaController : Controller
{ 
    private IServiceInvoker _serviceInvoker;
    public MediaController(IServiceInvoker serviceInvoker)
    {
        _serviceInvoker = serviceInvoker;
    }

    public JsonResult GetAllMedia()
    {
        var media = _serviceInvoker.InvokeService<IMediaService, List<MediaBase>>(proxy    => proxy.GetAllMediaInJson());

        JsonResult jsonResult = new JsonResult();
        jsonResult.Data = media;
        jsonResult.JsonRequestBehavior = JsonRequestBehavior.AllowGet;
        return jsonResult;

}


[TestClass]
public class MediaControllerTests
{
    [TestMethod]
    public void GetAllMedia()
    {
        JsonResult data;
        var serviceInvoker = MockRepository.GenerateStub<IServiceInvoker>();
        var media = CreateSeveralMedia();
        serviceInvoker.Stub(c => c.InvokeService<IMediaService, List<MediaBase>>(p => p.GetAllMediaInJson())).Return(media);
        data = new MediaController(serviceInvoker).GetAllMedia();
        serviceInvoker.VerifyAllExpectations();
        Assert.IsNotNull(data);
    }

}

我正在对服务进行存根并返回集合.当我运行此测试时,media为空.任何想法,我该如何对这个模拟游戏设定期望?

解决方法:

刚刚找到解决方案.看起来有点丑陋,但这是第一次迭代,可能很快才会出现更优雅的版本.该想法是创建另一个存根并匹配Func.反对:
我将为用例提供代码:

[Theory]
[InlineData(342, 31129, 3456)]
public void should_call_service_invoker_and_return_result(int number1, int number2, int expected)
{
    var calculator = MockRepository.GenerateStub<ICalculator>();
    calculator.Stub(_ => _.Add(number1, number2)).Return(expected);
    var serviceInvoker = MockRepository.GenerateStub<ServiceInvoker<ICalculator>>();
    serviceInvoker
        .Stub(_ => _.Invoke(Arg<Func<ICalculator, int>>.Matches(d => d(calculator) == calculator.Add(number1, number2))))
        .Return(expected);
    var serviceConsumer = new ServiceConsumer(serviceInvoker);

    var actual = serviceConsumer.GetAddResultFor(number1, number2);

    Assert.Equal(expected, actual);
}

xUnit扩展用作测试框架.请忽略Theory和InlineData的东西-这是摆脱不必要的测试设置的另一种方法.

这是SUT的代码:

public class ServiceConsumer
{
    private readonly ServiceInvoker<ICalculator> serviceInvoker;

    public ServiceConsumer(ServiceInvoker<ICalculator> serviceInvoker)
    {
        this.serviceInvoker = serviceInvoker;
    }

    public int GetAddResultFor(int number1, int number2)
    {
        return serviceInvoker.Invoke(_ => _.Add(number1, number2));
    }
}

public class ServiceInvoker<T>
{
    public virtual R Invoke<R>(Func<T, R> func)
    {
        throw new NotImplementedException();
    }
}

public interface ICalculator
{
    int Add(int number1, int number2);
}

希望这会有所帮助.欢迎任何有关增加更多美丽的建议:)

标签:rhino-mocks-3-5,c,rhino-mocks
来源: https://codeday.me/bug/20191208/2092088.html