This is a migrated thread and some comments may be shown as answers.

Mocking File.Exists

3 Answers 888 Views
General Discussions
This is a migrated thread and some comments may be shown as answers.
Matthew
Top achievements
Rank 1
Matthew asked on 03 Jul 2014, 03:39 PM
If this has been answered already you can just direct me there...

In the method i am working on I am trying to mock a "checkpoint".

the line of code is this....    if (File.Exists(filePath)){
rest of code is here
}
I need to mock this so the program just moves on regardless of if there is a file there or not.

Any suggestions?

3 Answers, 1 is accepted

Sort by
0
Matthew
Top achievements
Rank 1
answered on 03 Jul 2014, 03:42 PM
I also think I should have added that this "check" sits inside of a Private Method. I currently can access it and intercept the method it calls on later. I just need to mock the File.Exists
0
Kaloyan
Telerik team
answered on 08 Jul 2014, 10:51 AM
Hello Matthew,

To mock the File.Exists function, you can use the following syntax:
Mock.Arrange(() => File.Exists(Arg.AnyString)).Returns(true);

Further, I have prepared a small sample test for you, that should explain this in details. Here is the SUT we have:
public class Foo
{
    public string filePath { get; set; }
    public string result { get; set; }
 
    public Foo(string str)
    {
        this.filePath = str;
        this.result = "Fail!";
    }
    public void CheckIfExists()
    {
        if (File.Exists(this.filePath))
        {
            this.result = "Success!";
        }
    }
}

The Foo class has only one method that changes a string property if the File.Exists function returns true. Next is the test method, where the File.Exists is mocked to constantly return true in the scope of the test:
[TestMethod]
public void ShouldCheckIfFileExistsIsMocked()
{
    // Arrange
    Mock.Arrange(() => File.Exists(Arg.AnyString)).Returns(true);
 
    // Act
    var mock = new Foo("filePath");
    mock.CheckIfExists();
 
    // Assert
    Assert.AreEqual("Success!", mock.result);
}
The test passes with enabled profiler.

I hope this helps.

Regards,
Kaloyan
Telerik
 

Check out the Telerik Platform - the only platform that combines a rich set of UI tools with powerful cloud services to develop web, hybrid and native mobile apps.

 
0
Matthew
Top achievements
Rank 1
answered on 10 Jul 2014, 03:05 PM
It helped a lot thank you. I was also able to take what you posted and used it in a couple areas that needed "file" mocking. 
Tags
General Discussions
Asked by
Matthew
Top achievements
Rank 1
Answers by
Matthew
Top achievements
Rank 1
Kaloyan
Telerik team
Share this question
or