UnitTests: read an image

My function looks more or less like this:

protected readonly IWebHostEnvironment _env;

public byte[] GetDefaultImage()
{
	var webRoot = _env.WebRootPath;
	var placeholder = "img/default.png";
	var file = System.IO.Path.Combine(webRoot, placeholder);
	var userImage = System.IO.File.ReadAllBytes(file);
	return userImage;
}

To test this with xUnit there is the problem that WebRoot does not contain the correct path. IWebHostEnvironment can be mocked, but that helps only if it returns the correct path. What I decided on was to copy my image file to /Resources/img/default.png .

My mocked HostEnvironment looks like this:

public static IWebHostEnvironment GetMockWebHostEnvironment()
{
	var mockEnvironment = new Mock<IWebHostEnvironment>();
	var dirName = GetApplicationRoot();
	mockEnvironment
		.Setup(m => m.WebRootPath)
		.Returns(dirName+"\\Resources");
	return mockEnvironment.Object;
}

The important part is GetApplicationRoot, which I found here and it looks like this:

public static string GetApplicationRoot()
{
	var exePath = Path.GetDirectoryName(System.Reflection
				  .Assembly.GetExecutingAssembly().CodeBase);
	Regex appPathMatcher = new Regex(@"(?<!fil)[A-Za-z]:\\+[\S\s]*?(?=\\+bin)");
	var appRoot = appPathMatcher.Match(exePath).Value;
	return appRoot;
}

And now the test works, even in my build pipeline.

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.