简体   繁体   中英

How to mock 'out' parameter?

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);
}

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM