Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
132 views
in Technique[技术] by (71.8m points)

c# - Mock.Verify with FileInfo as Parameter

In my .Net Testproject I am implementing a test to verify if my implementation is called correctly

My Interface

public IExecution
{
    bool ExecuteProgram(FileInfo exeFile, string arguments);
}

My Test

public void TestSomething()
{
     var programExecMock = new Mock<IExecution>();
     programExecMock.Setup(pe => pe.ExecuteProgram(It.IsAny<FileInfo>(), It.IsAny<string())).Returns(true);

     // Create the System under test "sut"
     sut.CallSomething();

     programExecMock.Verify(pe => pe.ExecuteProgram(new FileInfo("C:\Path\To\An\Exe.exe"), "--myParam 1"), Times.Once);
}

When I try this test i get following Error:

Expected invocation on the mock once, but was 0 times: pe => pe.ExecuteProgram(C:PathToAnExe.exe, "--myParam 1")

Performed invocations:

  • MockIExecution:1 (pe):
  • IExecution.ExecuteProgram(C:PathToAnExe.exe, "--myParam 1")

Am I missing something? Thanks for your help!

question from:https://stackoverflow.com/questions/65913636/mock-verify-with-fileinfo-as-parameter

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

With new FileInfo("C:\Path\To\An\Exe.exe") you are creating a new object reference so what was executed with It.IsAny<FileInfo>() and new FileInfo are not same.

You can change the code as follows to use the same object.

public void TestSomething()
{
     var programExecMock = new Mock<IExecution>();
     var fileInfo = new FileInfo("C:\Path\To\An\Exe.exe");
     var args = "--myParam 1";
     programExecMock.Setup(pe => pe.ExecuteProgram(fileInfo, args )).Returns(true);

     // Create the System under test "sut"
     sut.CallSomething();

     programExecMock.Verify(pe => pe.ExecuteProgram(fileInfo , args ), Times.Once);
}

Or alternatively change to following

programExecMock.Verify(pe => pe.ExecuteProgram(It.IsAny<FileInfo>(), It.IsAny<string()), Times.Once);

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

57.0k users

...