Introduction
Sometimes, the logic of unit tests requires to work with resources which are embedded into the library. Most likely, it could be a file keeping initial data for black box which is tested by unit test. This post will show how to work with those kind of resources.
Background
Let's imagine we need to write unit test which verifies if black box fires exception for an empty file. As soon as test project is created in Visual Studio, we add empty test.dat file to Resources folder.
"Build Action" property for that resource must be set as "Embedded Resource" which implies that this file is embedded in the executable.
Using the Code
We can read resource as a stream with only one method extension GetEmbeddedResourceStream
passing parameter as a path to resource "Resources.test.dat". The unit test expects that BlackBox
class fires exception in Operation
method at reading of the fetched resource.
namespace EmbeddedResource_demo
{
public class BlackBox
{
public void Operation(Stream stream)
{
if (stream.Length == 0)
throw new ArgumentException("Stream is empty");
}
}
[TestClass]
public class UnitTest1
{
[TestMethod]
[ExpectedException(typeof(ArgumentException), "Stream is empty")]
public void TestFileIsEmpty()
{
using (var inputStream =
Assembly.GetExecutingAssembly().GetEmbeddedResourceStream("Resources.test.dat"))
{
var blackbox = new BlackBox();
blackbox.Operation(inputStream);
}
}
}
}
Add class AssemblyExtensions
to define the new method which returns the stream of data for embedded resource file.
public static Stream GetEmbeddedResourceStream
(this Assembly assembly, string relativeResourcePath)
{
if (string.IsNullOrEmpty(relativeResourcePath))
throw new ArgumentNullException("relativeResourcePath");
var resourcePath = String.Format("{0}.{1}",
Regex.Replace(assembly.ManifestModule.Name, @"\.(exe|dll)$",
string.Empty, RegexOptions.IgnoreCase), relativeResourcePath);
var stream = assembly.GetManifestResourceStream(resourcePath);
if (stream == null)
throw new ArgumentException(String.Format("The specified embedded resource
\"{0}\" is not found.", relativeResourcePath));
return stream;
}
Parameter assembly
represents the assembly which contains the resource. Parameter relativeResourcePath
represents the relative path for embedded resource file.
History
- 14th January, 2020: Initial version