question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

Finding it hard to mock some of the Storage classes

See original GitHub issue

Hi Team!

I’m finding it frustrating when mocking out some of the methods in the Storage SDK because a select number of them aren’t virtual.

For example - i’m referencing the code from the Getting Started docs.

I’m assuming that the methods that are not virtual are defined like that because they don’t need to hit the internet but just do some logic on the preset internal data?

Lets start with this:

REFERENCE: Here’s the full gist.

(Click to expand) Main method that does the code

private static void DoSampleTest(CloudFileClient fileClient)
{
    if (fileClient == null)
    {
        throw new ArgumentNullException(nameof(fileClient));
    }

    // Get a reference to the file share we created previously.
    CloudFileShare share = fileClient.GetShareReference(ShareName);

    // Ensure that the share exists.
    if (share.Exists())
    {
        // Get a reference to the root directory for the share.
        CloudFileDirectory rootDir = share.GetRootDirectoryReference();

        // Get a reference to the directory we created previously.
        CloudFileDirectory sampleDir = rootDir.GetDirectoryReference(DirectoryName);

        // Ensure that the directory exists.
        if (sampleDir.Exists())
        {
            // Get a reference to the file we created previously.
            CloudFile file = sampleDir.GetFileReference(FileName);

            // Ensure that the file exists.
            if (file.Exists())
            {
                // Write the contents of the file to the console window.
                Console.WriteLine(file.DownloadTextAsync().Result);
            }
        }
    }
}

☝️ That is literally a copy/paste of the MSDN sample docs code. The only exception is that the CloudFileClient instance is passed in. So we can pass in either:

  • A real instance, that hit the interwebs.
  • A mocked instance ✨ 💖

(Click to expand) The real code that hits Azure for real, yo!

[Fact]
public void IntegrationTest()
{
    // Parse the connection string and return a reference to the storage account.
    CloudStorageAccount storageAccount = CloudStorageAccount.Parse(...snipsnipsnipsnip....");

    // Create a CloudFileClient object for credentialed access to File storage.
    CloudFileClient fileClient = storageAccount.CreateCloudFileClient();
    DoSampleTest(fileClient);
}

(Click to expand) Finally - the mocked version

[Fact]
public void Test2()
{
    var file = new Mock<CloudFile>();
    file.Setup(x => x.Exists(null, null))
        .Returns(true);
    file.Setup(x => x.DownloadTextAsync())
        .ReturnsAsync("some file content");

    var sampleDir = new Mock<CloudFileDirectory>();
    sampleDir.Setup(x => x.Exists(null, null))
                .Returns(true);
    sampleDir.Setup(x => x.GetFileReference(FileName))
                .Returns(file.Object);

    var rootDir = new Mock<CloudFileDirectory>();
    rootDir.Setup(x => x.GetDirectoryReference(DirectoryName))
            .Returns(sampleDir.Object);

    var share = new Mock<CloudFileShare>();
    share.Setup(x => x.Exists(null, null))
            .Returns(true);
    share.Setup(x => x.GetRootDirectoryReference())
            .Returns(rootDir.Object);

    var fileClient = new Mock<CloudFileClient>();
    fileClient.Setup(x => x.GetShareReference(ShareName))
                .Returns(share.Object);

    DoSampleTest(fileClient.Object);
}

So nothing crazy wazzy pants at all.

But because of the non-virtual methods, The mock code fails at run-time.

For example:

// Get a reference to the file share we created previously.
CloudFileShare share = fileClient.GetShareReference("logs");

The GetShareReference method on a CloudFileClient isn’t virtual, so I can’t mock that. So, is there some trick so it can return a fake reference without having to really go off an hit the internet?

Next is this one…

// Get a reference to the root directory for the share.
CloudFileDirectory rootDir = share.GetRootDirectoryReference();

So this is a reference to the root Share directory. Again, this method is not virtual 😕 Again, is there some trick here that it doesn’t need to be virtual BUT also shouldn’t hit the interwebs…

So yeah … any idea’s folks?

Or am I just using the SDK incorrectly and failed to find the write samples/docs, about this?

Issue Analytics

  • State:closed
  • Created 7 years ago
  • Comments:5 (1 by maintainers)

github_iconTop GitHub Comments

3reactions
PureKromecommented, Oct 6, 2016
  1. Ah! binary - I didn’t think of that (out of sight, out of mind, etc…) - gotcha
  2. Oh totally dude! Totally ok!

Would love:

  • Some tags added to some issues/PR’s for M8. This helps me/us get some transparency over the next release 🙏
  • A rough and conservative date for M8 added to that milestone, plz?

and some token love …

0reactions
PureKromecommented, Oct 7, 2016

Another question related to this…

I’m trying to do a simple MOVE of a file. So i’ll COPY it then DELETE the original. Great! So this means I would do something like this…

CloudFile sourceFile = sampleDir.GetFileReference("someFile.txt");

That’s ok - but now I need to access the CloudFile Name property … but that’s always "". But this is a mock, so who cares … i can just mock that property … but … that property is not virtual 😦

Reason: given a CloudFile, I need to make sure all the subdirectories exist before I can move the file. I was using the Name field to get this data, split on / and then check/create each directory.

So could those properties on a CloudFile also be considered to be made virtual, too?

Read more comments on GitHub >

github_iconTop Results From Across the Web

Finding it hard to mock some of the Storage classes
Hi Team! I'm finding it frustrating when mocking out some of the methods in the Storage SDK because a select number of them...
Read more >
In Java unit testing, how to mock the variables that are not ...
In Java unit testing, how to mock the variables that are not injected but created inside the to-be-tested class? · If you're using...
Read more >
When mocking a class in a unit test, how should I handle ...
You may find you still need to specifically mock some tests where you want the dependency to throw an exception or return some...
Read more >
How can I mock a file storage abstraction? : r/golang
Hi, Im struggling to find a way to unit test some code I wrote for storage. Each file has a provider attached to...
Read more >
Mocking browser APIs in Jest (localStorage, fetch and more!)
Turns out, Jest gives you access to all sorts of browser APIs (fetch, localStorage, etc) that you can mock at a moment's notice!...
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found