Mocking File.Exists

4 posts, 0 answers
  1. Matthew
    Matthew avatar
    16 posts
    Member since:
    Jun 2014

    Posted 03 Jul 2014 Link to this post

    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?
  2. Matthew
    Matthew avatar
    16 posts
    Member since:
    Jun 2014

    Posted 03 Jul 2014 in reply to Matthew Link to this post

    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
  3. DevCraft R3 2016 release webinar banner
  4. Kaloyan
    Admin
    Kaloyan avatar
    872 posts

    Posted 08 Jul 2014 Link to this post

    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.

     
  5. Matthew
    Matthew avatar
    16 posts
    Member since:
    Jun 2014

    Posted 10 Jul 2014 in reply to Kaloyan Link to this post

    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. 
Back to Top