Mocking a ConfigurationSection (or full configuration file)

In unit-tests you sometimes find yourself in a situation that you need to mock a configuration section. The ConfigurationSection class (or your inherited class) encapsulates nicely and there is no easy way how to break it’s read-only public interface.

You might consider abstracting the whole section and/or exposing it via some kind of adapter, but sometimes you don’t need to be 100% pure and still want get some basic test coverage.

There is an obscure but functional way how to mock the ConfigurationSection (or a whole configuration file if needed):

1. Create a fake configuration file in your test project

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
	<configSections>
<section name="mySection" type="MyConfigurationSection, MyAssembly" />
	</configSections>
	<mySection>
		<identities>
			<identity clientId="fake_id" name="FAKE_NAME" partitionName="FAKE_PARTITION" permissions="Full" />
		</identities>
	</mySection>
</configuration>

The file can be placed in any directory in test project. Right beside your test-class might be the right place.

2. Set the configuration file to be copied to build output

In Properties of the configuration file, set:

  • Build Action = Content
  • Copy to Output Directory = Copy always

3. Create a unit-test which uses the file to build a fake configuration

[TestClass]
public class MyServiceTests
{
	public TestContext TestContext { get; set; }

	[TestMethod]
	[DeploymentItem("PathInTestProject\\MyServiceTests_ScenarioName.config")]
	public void MyService_DoSomething_ScenarioName_ExpectedBehavior()
	{
		// arrange
		ExeConfigurationFileMap configFileMap = new ExeConfigurationFileMap()
		{
			ExeConfigFilename = Path.Combine(TestContext.DeploymentDirectory, "MyServiceTests_ScenarioName.config")
		};
		Configuration config = ConfigurationManager.OpenMappedExeConfiguration(configFileMap, ConfigurationUserLevel.None);
		MyConfiguarionSection mySection = config.GetSection("mySection") as MyConfiguarionSection ;

		var sut = new MyService(mySection);

		// act
		...
	}
}

The basics:

  • The ConfigurationManager.OpenMappedExeConfiguration() method allows you to use any configuration file you want.
  • The [DeploymentItem(...)] attribute copies the config file from build output to the “test deployment directory” (e.g. $(SolutionDir)\TestResults\Deploy_username 2017-09-29 22_02_39\Out\)
  • The TestContext.DeploymentDirectory contains the path whereas the TestContext property is automatically injected with appropriate instance of the test context.

 

 

Azure: Checking if a blob exists using its URI

Having only a storage account (CloudBlobClient) and a blob URI makes it a little bit tricky to check if the blob actually exists. To be able to use the ​​ICloudBlob.Exists()​ method, you have to have a blob-reference and there is no easy way to get it from URI.

If you just need to know if the blob exists, you can make a simple HTTP HEAD request to the URI with any HTTP client.

If you need the blob-reference for further use, there is a CloudBlobClient.GetBlobReferenceFromServer(Uri blobUri) method. As you call it, it hits the server with a HEAD request and throws an exception if the blob does not exist (so there is no chance to use the Exists method later).

You can catch this exception with a nice pattern-matching:

ICloudBlob blob;
try
{
    blob = blobClient.GetBlobReferenceFromServer(new Uri(url));
}
catch (Microsoft.WindowsAzure.Storage.StorageException ex)
            when ((ex.InnerException is System.Net.WebException wex)
                    && (wex.Response is System.Net.HttpWebResponse httpWebResponse)
                    && (httpWebResponse.StatusCode == System.Net.HttpStatusCode.NotFound))
{
    // blob does not exist, do whatever you need here
    return null;
}
// further code able to use the blob-reference

Visual Studio: Keyboard shortcuts to navigate to next/previous member in code

In Resharper there is a well known keyboard shortcut to navigate to next (Alt+Down) or previous (Alt+Up) member in code.

In plain Visual Studio (at least in VS2017+) you are able to add these shortcuts easily. There are Edit.NextMethod and Edit.PreviousMethod commands which used to be available only for Visual Basic editor. Nowadays, as C# and Visual Basic are widely aligned, they are fully functional in C# code as well:

2017-09-26_10-12-19

I will probably go for Ctrl+Up, Ctrl+Down which are bound to Scroll-Up/Down by default.