Home > Blockchain >  SetupSequence moq for different file string paths C#
SetupSequence moq for different file string paths C#

Time:05-23

I have 2 different file paths which I read 'last write time':

var current1TimeStamp = File.GetLastWriteTime(path)(file1);
var current2TimeStamp = File.GetLastWriteTime(path)(file2);

I want to setup a mock sequence but I have a problem:

var fileServiceMock = new Mock<IFile>(MockBehavior.Strict);
            fileServiceMock.SetupSequence(s => s.GetLastWriteTime())
                .Returns(System.DateTime.Now)
                .Returns(System.DateTime.Now);

What do I do wrong?

CodePudding user response:

As stated in my comment above, you should provide values for the parameters of the mocked method inside the lambda expression. If you do not care about the values passed, you can use the method It.IsAny<T>()

var fileServiceMock = new Mock<IFile>(MockBehavior.Strict);
fileServiceMock.SetupSequence(s => s.GetLastWriteTime(It.IsAny<string>()))
    .Returns(System.DateTime.Now)
    .Returns(System.DateTime.Now);

Your current setup will return the same value (possibly give or take a microsecond) for the first two calls to the mocked method. Maybe it would be better to use Setup instead of SetupSequence since you don't really care about the number of calls here? Or you could set up different return values based on the path input, as follows:

var fileServiceMock = new Mock<IFile>(MockBehavior.Strict);
fileServiceMock.Setup(s => s.GetLastWriteTime("path/to/file1"))
  .Returns(someDateTime);
fileServiceMock.Setup(s => s.GetLastWriteTime("path/to/file2"))
  .Returns(someOtherDateTime);
  • Related