How to mock 'out' parameter?

2019-05-08 18:38发布

I have downloaded the latest NSubstitute release, 1.1.0, May 21, 2011. Prior to this release, it seems that NSub did not support out parameters. It appears that some work has been done to provide support through an intermediate release: NSub Google Group.

So, I am having a little trouble trying to get all the pieces working. I am using SystemWrapper to mock DirectoryInfo

Here is my interface:

    public interface INetworkPath
    {
        void SetPath(string NetworkPath);
        bool TryGetDirectoryInfo(out IDirectoryInfoWrap DirectoryInfo);
    }

...and the test:

public void SetNetworkPath_SetDirectoryInfo()
{
    var netPath = Substitute.For<INetworkPath>();
    netPath.SetPath("SomeNetworkPath");
    IDirectoryInfoWrap DirectoryInfo;

    netPath.TryGetDirectoryInfo(out DirectoryInfo)
           .Returns(d => {   // cannot convert lambda expression to type bool because it is not a delegate type
               d[1] = Substitute.For<IDirectoryInfoWrap>();  //  d[1] is read only
               return true;
           });

    Assert.IsNotNull(DirectoryInfo);
}

Is there a way to mock the out parameter from the INetworkPath interface?

Update

Tried the following: although it compiles, DirectoryInfo returns null:

[Test]
public void SetNetworkPath_SetDirectoryInfo()
{
    var netPath = Substitute.For<INetworkPath>();
    netPath.SetPath("SomeNetworkPath");
    IDirectoryInfoWrap DirectoryInfo;

    netPath.TryGetDirectoryInfo(out DirectoryInfo)
           .Returns(d => { 
               d = (CallInfo)Substitute.For<IDirectoryInfoWrap>();
               return true;
           });

    Assert.IsNotNull(DirectoryInfo);
}

1条回答
该账号已被封号
2楼-- · 2019-05-08 19:04

I don't believe the implementation you are looking for was released with 1.1 but done afterwards (Ref and out support commit). You will probably have to do a pull of the code and build it yourself.

查看更多
登录 后发表回答