Rhino Mocks - Arg <t>省略一些参数

时间:2016-01-29 07:50:42

标签: c# unit-testing arguments parameter-passing rhino-mocks

我正在使用Rhino Mocks来删除SOAP端点的功能,并且大多数情况下它都有效。但是,界面非常古怪,我正在努力让以下工作(我为了简单而重命名了这些类)

  public interface IWebService
    {
        void CopyFile(Request request);
    }

public interface IService
{
    void CopyFile(string filename, byte[] data);
}

public class Request
{
    public string Filename { get; set; }
    public byte[] Data { get; set; }
}
public class Service : IService
{
    IWebService _service;
    public Service(IWebService service)
    {
        _service = service;
    }
    public void CopyFile(string filename, byte[] data)
    {
        _service.CopyFile(new Request() {Filename = filename,Data = data });
    }
}

现在,在我的测试中,我有类似的东西

[TestCase]
        public void TestFileCopyFailsIfFilenameIsMissing()
        {
            IWebService serviceMock = MockRepository.GenerateMock<IWebService>();
            serviceMock.Expect(x => x.CopyFile(Arg<Request>.Is.Equal(new Request() { Filename = Arg<string>.Is.Null, Data = Arg<byte[]>.Is.Anything }))).Throw(new Exception());

            Service service = new Service(serviceMock);
            service.CopyFile(null, new byte[] { });

        }

抛出异常: 类型&#39; System.InvalidOperationException&#39;的例外情况发生在Rhino.Mocks.dll但未在用户代码中处理

附加信息:录制时,在模拟方法调用中仅使用Arg。预期有1个参数,已经定义了3个。

我已经在这个世界上尝试了所有可能性,但是无法做到正确。如果我不使用Arg并使用

Expect(null, new byte[]{});
无论什么

,它总会通过

2 个答案:

答案 0 :(得分:0)

我建议使用WhenCalled,并在此方法中检查Request对象。

        bool isCorrectParam = false;

        IWebService serviceMock = MockRepository.GenerateMock<IWebService>();
          serviceMock.Expect(x => x.CopyFile(null))
              .IgnoreArguments()
              .WhenCalled(x =>
              {
                  Request req = x.Arguments[0] as Request;
                  if (req.Data.Count() == 0 && req.Filename == null)
                  {
                      isCorrectParam = true;
                  }
              });

        Service service = new Service(serviceMock);
        service.CopyFile(null, new byte[] { });

        Assert.IsTrue(isCorrectParam);

答案 1 :(得分:0)

您也可以使用匹配...

serviceMock.Expect(x => x.CopyFile(Arg<Request>.Matches(r => r.FileName==null))).Throw(new Exception());