In a previous question Does Nancy.Testing support nested Razor views? I outlined the difficulties I was having with Nancy unit tests failing when presented with nested razor layouts.
After investigation I can now refine that information. The problem is not related to nesting it is simply this: If you include a @using statement in a razor layout or view, then Nancy will fail to find that referenced namespace if accessed from a unit-test.
For example:
Master Layout
@inherits Nancy.ViewEngines.Razor.NancyRazorViewBase<dynamic>
<!DOCTYPE html>
<html lang="en">
<head>
<title>Test</title>
</head>
<body>
@RenderBody()
</body>
</html>
View
@inherits Nancy.ViewEngines.Razor.NancyRazorViewBase<dynamic>
@{
Layout = "Master.cshtml";
}
hello World
As you would expect, this works fine. However if we now add a bit of server side processing to the master layout, and so create the need for a @using statement, then unit tests fail (the code runs fine normally, only the unit tests fail) with:
Error Compiling Template: (15, 11) The type or namespace name 'uMentor' could not be found.
Master Layout with server-side code
@inherits Nancy.ViewEngines.Razor.NancyRazorViewBase<dynamic>
@using uMentor.Extensions
<!DOCTYPE html>
<html lang="en">
<head>
<title>@Model.Title</title>
</head>
<body>
@{
var user = Html.GetCurrentUser();
}
@RenderBody()
</body>
</html>
I have ensured that my web.config (both the web-site project and the unit-test project) have the correct razor assemblies and namespaces mentioned:
Web.config
<configSections>
<section name="razor" type="Nancy.ViewEngines.Razor.RazorConfigurationSection, Nancy.ViewEngines.Razor" />
</configSections>
<razor disableAutoIncludeModelNamespace="false">
<assemblies>
<add assembly="System, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" />
<add assembly="Nancy" />
<add assembly="uMentor" />
</assemblies>
<namespaces>
<add namespace="Nancy" />
<add namespace="uMentor" />
<add namespace="uMentor.Domain" />
<add namespace="uMentor.Extensions" />
</namespaces>
</razor>
Stripping everything back, I can build the simplest 'hello world' view -> layout with nothing in it, no code. The unit test passes (the response body has the correct html in it). I then put in a redundant @using statement at the top of the view or the layout and the test fails (the response body contains the error message above).
Master Layout with @using only - Fails
@inherits Nancy.ViewEngines.Razor.NancyRazorViewBase<dynamic>
@using uMentor.Extensions
<!DOCTYPE html>
<html lang="en">
<head>
<title>Test</title>
</head>
<body>
@RenderBody()
</body>
</html>
Therefore, the evidence suggests that placing a @using statement into a razor view or layout causes a razor compilation error that silently fails, returning the error message in the response body. Only if your test happens to check the body content will you find out there has been a problem.
Thank you for any help.