简体   繁体   中英

Visual Studio: Revoke reading permission of test file for Unit Testing

I am working on a Visual Studio (Community 2015) project in C# that reads metadata from video files. Therefore I want to write a Unit Test that tests if the program handles an inaccessible file the right way. So I want to add a test file to my test data for which the Unit Test does not have read permissions.

But what is the best way to do this? I didn't find any option to set permissions in Visual Studio. The only idea I have at the moment is to revoke reading permissions directly in the properties of the file. Through the Windows File Explorer, thus outside of Visual Studio. But then I wouldn't be able to read the file myself. Also, it doesn't seem to be the right way and I think there should be a more clean way to solve this problem directly in Visual Studio.

Any ideas?

If you are writing a unit test then it should just check if your code is written correcly and not about the external issues which are difficult to replicate or may not be available on other machines. So I think you should read about Dependency Injection and how to do mock dependencies in your test. I can give you an easy to understand example but please do write it in your words.

public interface IFileReader
{
    string ReadFile( string filePath );
}


public class FileReader : IFileReader
{
    public string ReadFile( string filePath )
    {
        return System.IO.File.ReadAllText( filePath );
    }
}

So Suppose you have a class VideoMetaDataReader then in that class you will inject the interface as a dependency and use the ReadFile method to read. And then in your test

[TestFixture]
    public class FileReaderTests
    {
        [Test]
        public void ShouldDisplayANiceMessage_WhenFileIsInaccessible()
        {
            var moq = new Moq.Mock<IFileReader>();
            moq
                .Setup( x => x.ReadFile( Moq.It.IsAny<string>() ) )
                .Throws<Exception>();

            var metaDataReader = new MetaDataReader( moq.Object );
            metaDataReader.ReadVideoFile( "video.mp4" );
            Assert.AreEqual( 1, meaDataReader.Errors.Count );    
        }
    }

I am assuming there will be a errors property which will return encountered errors but it depends how you want to do it (I didn't think too much on this).

Anyways, the point is don't test what is not covered by your code. What your code needs to do is to display a nice message if there is an exception and that you can do if you mock the interface (which means don't call the actual implementation and instead do something which I want in this test) and then check if your code can handle that. btw i used nunit and moq for test and mocking.

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