I want to unit test my cshtml files to ensure they compile successfully as recently I've had some issues where at run time there were failures due to the views expecting properties that weren't present. I am trying to use RazorEngine to check this, and here is my attempt at a unit test:
public void LayoutCshtml_AnyCase_ViewCompilesSuccessfully()
{
var model = new Model();
var templateName = File.ReadAllText("PathToView/_Layout.cshtml");
var result = Engine.Razor.RunCompile(templateName, "key", typeof(Model), model);
//Assertion will go here
}
I will add the assertion later but at the moment just want the view to compile. The templateName correctly picks up the right .cshtml but the result fails because of error:
The predefined type
'System.Runtime.CompilerServices.ExtensionAttribute' is defined in
multiple assemblies in the global alias;
Is anyone familiar with using RazorEngine to test please?
Related
I have the following code
this.SafeUpdate(rate, Guid.Parse(import.myGuid), c => c.myGuid);
SafeUpdate basically takes the parsed guid value and applies it to the myGuid property on the rate object. This works fine from my front end, but throws the "CLR detected..." error when run in a unit test. What's odd is the same statement for DateTime.Parse and int.Parse works fine. It just fails for Guid and decimals. I don't believe the error is with the parsing (it has the correct parsed value when extracted into a separate variable). I don't believe it's the mocking either as the statement works fine for all other types other than guid and decimal. Any ideas?
We experienced a similar error yesterday on our build server. Our exception was thrown by the ReadObject() method of a DataContractSerializer.
System.InvalidProgramException: Common Language Runtime detected an invalid program.
at System.Xml.EncodingStreamWrapper..ctor(Stream stream, Encoding encoding)
at System.Xml.XmlUTF8TextReader.SetInput(Stream stream, Encoding encoding, XmlDictionaryReaderQuotas quotas, OnXmlDictionaryReaderClose onClose)
at System.Xml.XmlDictionaryReader.CreateTextReader(Stream stream, Encoding encoding, XmlDictionaryReaderQuotas quotas, OnXmlDictionaryReaderClose onClose)
at System.Xml.XmlDictionaryReader.CreateTextReader(Stream stream, XmlDictionaryReaderQuotas quotas)
at System.Runtime.Serialization.XmlObjectSerializer.ReadObject(Stream stream)
We've written a console app that does just this one thing. It runs without error, but fails in a simple unit test. We are using Gallio/MbUnit 3.4.11.0 for our test framework with a target of .net 4.0.
using System;
using System.IO;
using System.Runtime.Serialization;
using MbUnit.Framework;
namespace TestApp
{
[TestFixture]
class Program
{
static void Main()
{
FooBar();
Console.ReadKey();
}
public static void FooBar()
{
var type = typeof(string);
var foo = "foo";
using (var stream = new MemoryStream())
{
var serializer = new DataContractSerializer(type);
serializer.WriteObject(stream, foo);
stream.Seek(0, SeekOrigin.Begin);
var deserializer = new DataContractSerializer(type);
var bar = deserializer.ReadObject(stream);
Console.WriteLine(bar);
}
}
[Test]
public void Test()
{
FooBar();
}
}
}
The application runs fine, but the test throws. Strangely, this test passes on my dev box but fails on our build server as well as the dev box of a coworker. Clearly, there is something different about my dev box that allows the test to pass, but I have not located that difference yet.
Update 1
The version of System.dll on my dev box is 4.0.30319.296 but on the build server and the dev box of my coworker it is 4.0.30319.1001. System.Xml.dll and System.Runtime.Serialization.dll are identical at 4.0.30319.1, however.
Update 2
A quick google search for "4.0.30319.1001" returns this security update, http://support.microsoft.com/kb/2742595, which was applied to both our build server and the dev box of my coworker, but not my dev box. I uninstalled the update on the build server, rebooted, and the issue went away! I guess Microsoft doesn't have a unit test for this one yet. :-)
I have just started learning asp.net mvc and one reason of the primary reasons has been to move to TDD.
I am writing a small dashboard application which has reports. In this app, I had a primary controller called ReportsController, which right now has just one method, GetReport that takes in a query and returns a view if the query meets certain conditions, else returns an error message.
[HttpGet]
public ActionResult GetReport(string query)
{
//calls the QueueRep and gets back DataTable
ReportQuery reportQuery = new ReportQuery(query);
if (reportQuery.IsValidQuery)
{
queryRepository.ExecuteReportQuery(ref reportQuery);
}
else
{
return View("Error");
}
ViewData.Add("ResultDataTable",reportQuery.ResultDataTable);
return View();
}
I had written 2 unit tests for this as follows
public void GetReport_Should_Return_Error_View_For_Malicious_Query()
{
//Arrange
string query = "drop table userInfo";
var controller = CreateReportsController(query);
//Act
var result = controller.GetReport(query) as ViewResult;
//Assert
Assert.AreEqual(result.ViewName, "Error");
}
[Test]
public void GetReport_Should_Return_View_With_DataTable_For_Correct_Query()
{
//Arrange
StringBuilder sb = new StringBuilder();
sb.Append("SELECT Year(CreatedOn) as Year, Month(CreatedOn) as Month, Count(CREATEDON) as NewEmployers");
sb.Append("FROM dbo.UserInfo WHERE DefaultPurpose = 1 GROUP BY Year(CreatedOn), Month(CreatedOn)");
string query = sb.ToString();
var controller = CreateReportsController(query);
//Act
var result = controller.GetReport(query) as ViewResult;
//Assert
Assert.IsTrue(result.ViewData.ContainsKey("ResultDataTable"));
Assert.IsTrue(result.ViewData["ResultDataTable"].GetType() == typeof(System.Data.DataTable));
}
Now, due to conflict with SSRS, the server/Reports was pointing to SSRS instead of Reports controller so I changed name of ReportsController to MyReportsController. I used refactor for the name change and changed my unit tests in the test project as well and ran the unit tests. Everything is fine.
But now when I ran actual app, I got an error. Basically, the folder name of the views had to be changed from Reports to MyReports. How can I test these kind of scenarios. Is only using functional testing tools like selenium? Or I could have written my tests differently?
I don't think there is anything you should/could do to test this with unit tests, but integration tests with Selenium is a good way to go about it:
http://seleniumtoolkit.codeplex.com/
Yes, manual testing or functional test tools like Selenium are the only way to find these breaking changes.
The reason is because with unit testing you are only testing small bite sized parts of your code. So testing a controller's action method is great! In that test you need to remember that your testing your own code and not the asp.net and/or mvc frameworks. Now, to -render- a view result, this is handled outside of your action method. Secondly, we assume that the rendering logic (how to render) has been tested by Microsoft so we don't want waste time testing that either.
So this means we need to join independent modules together in a single test. When we have 2+ modules or areas etc to test, we suddenly jump out of unit testing and into manual or functional testing.
I have MVC areas in external libraries which have their own area registration code just as a normal MVC area would. This area registration gets called for each dll (module) and I have verified the RouteTable contains all the routes from the loaded modules once loading has been completed.
When I reference these external areas in the main site they get pulled into the bin directory and load up fine. That is, when a request is made for a route that exists in an external library, the correct type is passed to my custom controller factory (Ninject) and the controller can be instantiated.
Once I move these dll's outside of the bin directory however (say to a Modules folder), there appears to be an issue with routing. I have checked that the RouteTable has all the required routes but by the time a request makes its way into the ninject controller factory the requested type is null. From reading here an SO link here this behaviour seems to occur when ASP.NET MVC cannot find the controller matching the requested route or does not know how to make sense of the route.
When loading the modules externally I have ensured that the modules that I want loaded are loaded into the app domain via a call to Assemby.LoadFrom(modulePath);
I did some research and it appears that when attempting to load a library outside of bin you need to specify private probing in app.config as pointed out here;. I have mine set to 'bin\Modules' which is where the mvc area modules get moved too.
Does anyone have any ideas why simply moving an mvc area project outside of the bin folder would cause the requested type passed into the controller factory to be null resulting in the controller to be instantiated?
Edit:
All routes registered in external areas have the namespace of the controller specified in the route
Below is a fragment of code that creates a new Ninject kernel, reads a list of module names from a file to enable, and then goes searching for the enabled modules in the bin/Modules directory. The module is loaded via the assembly loader, has its area(s) registered and then loaded into the ninject kernel.
// comma separated list of modules to enable
string moduleCsv = ConfigurationManager.AppSettings["Modules.Enabled"];
if (!string.IsNullOrEmpty(moduleCsv)) {
string[] enabledModuleList = moduleCsv.Replace(" ", "").Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries);
_Modules = enabledModuleList ?? new string[0];
// load enabled modules from bin/Modules.
var moduleList = Directory.GetFiles(Server.MapPath("~" + Path.DirectorySeparatorChar + "bin" + Path.DirectorySeparatorChar + "Modules"), "*.dll");
foreach (string enabledModule in enabledModuleList) {
string modulePath = moduleList.Single(m => m.Contains(enabledModule));
// using code adapted from from AssemblyLoader
var asm = AssemblyLoader.LoadAssembly(modulePath);
// register routes for module
AreaRegistrationUtil.RegisterAreasForAssemblies(asm);
// load into Ninject kernel
kernel.Load(asm);
}
}
This is the crux of the Ninject controller factory that receives the aforementioned Ninject kernel and handles requests to make controllers. For controllers that exist within an assembly in bin/Modules the GetControllerType(...) returns null for the requested controller name.
public class NinjectControllerFactory : DefaultControllerFactory
{
#region Instance Variables
private IKernel _Kernel;
#endregion
#region Constructors
public NinjectControllerFactory(IKernel kernel)
{
_Kernel = kernel;
}
protected override Type GetControllerType(System.Web.Routing.RequestContext requestContext, string controllerName)
{
// Is null for controller names requested outside of bin directory.
var type = base.GetControllerType(requestContext, controllerName);
return type;
}
protected override IController GetControllerInstance(System.Web.Routing.RequestContext requestContext, Type controllerType)
{
IController controller = null;
if (controllerType != null)
controller = _Kernel.Get(controllerType) as IController;
return controller;
}
}
Update on Ninject Nuget Install
I couldn't get it to install Ninject.MVC3 via NuGet for some reason. Visual Studio was giving some schemaVersion error when clicking the install button (I have installed other Nuget packages like ELMAH btw).
I did find out something else that was interesting though, and that is that if I pass in the extra module assembilies to the NinjectControllerFactory I have and search those when the type cannot be resolved it finds the correct type and is able to build the controller. This leads to another strange problem.
The first route to be requested from an external module is the /Account/LogOn in the auth and registration module. The virtual path provider throws an error here after it has located the view and attempts to render it out complaining of a missing namespace. This causes an error route to fire off which is handled by an ErrorHandling module. Strangely enough, this loads and render fine!
So I am still stuck with two issues;
1) Having to do a bit of a dodgy hack and pass in the extra module assemblies to the NinjectControllerFactory in order to be able to resolve types for Controllers in external modules
2) An error with one particular module where it complains about a namespace not being found
These two issues are obviously connected because the assembly loading just isn't loading up and making everything available that needs to be. If all these mvc areas are loaded from the bin directory everything works fine. So it is clearly a namespacing/assembly load issue.
LoadFrom load the assembly into the loading context. These types are not available to the other classes in the default Load context. Probably this is the reason why the controller is not found.
If you know which assemblies have to be loaded then you should always use Assembly.Load(). If you don't know which assemblies are depolyed in the directory then either guess from the filesnames the assembly names or use Assembly.ReflectionOnlyLoadFrom() (preferably using a temporary AppDomain) to get the assembly names. Then load the assemblies using Assembly.Load() with the assembly name.
If your assemblies contain NinjectModules you can also use kernel.Load() which does what I described above. But it only loads assemblies containing at least one module.
Read up http://msdn.microsoft.com/en-us/library/dd153782.aspx about the different assembly contexts.
Here is a small extract from the Ninject codebase. I removed the unnecessary stuff but did not try to compile or run so probably there are minor issues with this.
public class AssemblyLoader
{
public void LoadAssemblies(IEnumerable<string> filenames)
{
GetAssemblyNames(filenames).Select(name => Assembly.Load(name));
}
private static IEnumerable<AssemblyName> GetAssemblyNames(IEnumerable<string> filenames)
{
var temporaryDomain = CreateTemporaryAppDomain();
try
{
var assemblyNameRetriever = (AssemblyNameRetriever)temporaryDomain.CreateInstanceAndUnwrap(typeof(AssemblyNameRetriever).Assembly.FullName, typeof(AssemblyNameRetriever).FullName);
return assemblyNameRetriever.GetAssemblyNames(filenames.ToArray());
}
finally
{
AppDomain.Unload(temporaryDomain);
}
}
private static AppDomain CreateTemporaryAppDomain()
{
return AppDomain.CreateDomain(
"AssemblyNameEvaluation",
AppDomain.CurrentDomain.Evidence,
AppDomain.CurrentDomain.SetupInformation);
}
private class AssemblyNameRetriever : MarshalByRefObject
{
public IEnumerable<AssemblyName> GetAssemblyNames(IEnumerable<string> filenames)
{
var result = new List<AssemblyName>();
foreach(var filename in filenames)
{
Assembly assembly;
try
{
assembly = Assembly.LoadFrom(filename);
}
catch (BadImageFormatException)
{
// Ignore native assemblies
continue;
}
result.Add(assembly.GetName(false));
}
return result;
}
}
}
When testing an ASP.NET MVC 2 application I hit a problem when a view could not be located.
Looking at the code I realised that the aspx file for the view had not been added to the source control repository. On this project that's quite easy to do as we use StarTeam for source control and it doesn't show new folders when checking in. This view was for a new controller and so a new folder was created for it and it was therefore missed.
Our build server (using Hudson/MSBuild) didn't pick up on this, as the code still builds fine with the aspx file missing. Our controller unit tests test the ActionResults which obviously still pass without the view there.
This got picked up in system testing but how can I catch this earlier (ideally on the build server).
Thanks in advance
You can write unit tests that test the actual view, and then if the unit test doesn't pass on the build server, you know you have a problem. To do this, you can use a framework such as this:
http://blog.stevensanderson.com/2009/06/11/integration-testing-your-aspnet-mvc-application/
With this you can write unit tests such as this (from the post)
[Test]
public void Root_Url_Renders_Index_View()
{
appHost.SimulateBrowsingSession(browsingSession => {
// Request the root URL
RequestResult result = browsingSession.ProcessRequest("/");
// You can make assertions about the ActionResult...
var viewResult = (ViewResult) result.ActionExecutedContext.Result;
Assert.AreEqual("Index", viewResult.ViewName);
Assert.AreEqual("Welcome to ASP.NET MVC!", viewResult.ViewData["Message"]);
// ... or you can make assertions about the rendered HTML
Assert.IsTrue(result.ResponseText.Contains("<!DOCTYPE html"));
});
}
What version of StarTeam are you running? In StarTeam 2008 (not sure when this feature was first added) within a selected project/view, you can select from the menu Folder Tree->Show Not-In-View Folders. This will show folders you have on local disk that have not been added to the project (they will appear with the folder icon colored white).
This is an old question, but if anyone still looking for this you ought to try SpecsFor.Mvc by Matt Honeycutt.
Not only it can be used to make sure the Views are properly included/added in the source control, it can even do integration test to make sure those Views are valid.
Link to its website: http://specsfor.com/SpecsForMvc/default.cshtml
Link to the nuget package: https://www.nuget.org/packages/SpecsFor.Mvc/
Link to github: https://github.com/MattHoneycutt/SpecsFor
Here is a code snippet taken from the website showing how to use it.
public class UserRegistrationSpecs
{
public class when_a_new_user_registers : SpecsFor<MvcWebApp>
{
protected override void Given()
{
SUT.NavigateTo<AccountController>(c => c.Register());
}
protected override void When()
{
SUT.FindFormFor<RegisterModel>()
.Field(m => m.Email).SetValueTo("test#user.com")
.Field(m => m.UserName).SetValueTo("Test User")
.Field(m => m.Password).SetValueTo("P#ssword!")
.Field(m => m.ConfirmPassword).SetValueTo("P#ssword!")
.Submit();
}
[Test]
public void then_it_redirects_to_the_home_page()
{
SUT.Route.ShouldMapTo<HomeController>(c => c.Index());
}
[Test]
public void then_it_sends_the_user_an_email()
{
SUT.Mailbox().MailMessages.Count().ShouldEqual(1);
}
[Test]
public void then_it_sends_to_the_right_address()
{
SUT.Mailbox().MailMessages[0].To[0].Address.ShouldEqual("test#user.com");
}
[Test]
public void then_it_comes_from_the_expected_address()
{
SUT.Mailbox().MailMessages[0].From.Address.ShouldEqual("registration#specsfor.com");
}
}
}
I am using Linq to SQL in my project. I have a part of the code that calls
DataContext db = new DataContext()
This works as expected when running the website however when calling this from within my unit test I get an error object not set to an instance...
Do you know why this is?
I know I should Mock the data context for testing but there is only two tests that use this that I need completed for this stage of the project. Then I will go in and Mock.
I just don't see why it doesn't work.
Edit:
In my controller I have the line
CandidateRegistrationViewModel viewModel = new CandidateRegistrationViewModel("PersonalDetails", candidate);
The Model has a member db:
public class CandidateRegistrationViewModel
{
private EmployDirectDataContext db = new EmployDirectDataContext();
This class then uses db to populate select boxes.
It all works when I run but in the unit test I get an error upon creating the datacontext.
[TestMethod]
public void PersonalDetailsStepPostShouldRedisplayIfDOBSuppliedInWrongFormat()
{
// Arange
var controller = CreateCandidateController("Dean");
repository.Add(FakeCandidateData.CreateCandidate(controller.member.UserId()));
FormCollection formCollection = FakeCandidateData.CreatePersonalDetailsStepFormCollection();
formCollection["DOB"] = "24/2009/87"; //DOB in wrong format - should be dd/mm/yyyy
controller.ValueProvider = formCollection.ToValueProvider();
// Act
ViewResult result = (ViewResult)controller.PersonalDetailsStep(formCollection);
// Assert
Assert.AreEqual("", result.ViewName); //ViewName is returned as empty if same as Action name
}
Both of the projects have the same connection string in the app/web.config
<add name="EmployDirectDBConnectionString" connectionString="Data Source=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|\EmployedDirectDB.MDF;Integrated Security=True;User Instance=True"
providerName="System.Data.SqlClient" />
Testing the Data Context falls more into the purview of an Integration Test. The mocks are more appropriate for your repository interface. Your repository will hold a valid reference to the DataContext object during your integration testing.
Your unit test assembly probably does not have the right connectionstring compiled into the settings. That's why I always use:
var db = new MyDataContext(SomeConfigClassIMade.ConnString) {...}
so I can more tightly control how the connection string works,.
I an not sure why you would want to test the DataContext itself... (I may be wrong and I am sure someone will tell me if I am) but would you just test the DataAccess or Repository class that uses the DataContext...
Other than that it probably just doesn't have the correct connection string...