Rhino Mock vs debug mode? - c#

my problem is following:
I have ms unit test which uses stubbed http context for mvc routing tests. But one part of code (which uses rhino mock) is problematic:
var httpContextMock = MockRepository.GenerateStub<HttpContextBase>();
httpContextMock.Stub(c => c.Request.AppRelativeCurrentExecutionFilePath)
.Return(url);
In debug mode, second line throws an exception:
Why such an error occurs ? While tests are fired without debugger, everything works fine.
Regards

This is really weird. What's strange to me is that your code works in non-debug mode. The Request property is not stubbed, so you can't really know what it would return. You may try the following:
var httpContextMock = MockRepository.GenerateStub<HttpContextBase>();
var httpRequestMock = MockRepository.GenerateStub<HttpContextBase>();
httpContextMock.Stub(c => c.Request).Return(httpRequestMock);
httpRequestMock.Stub(c => c.AppRelativeCurrentExecutionFilePath).Return(url);

I was having this issue with mine as well, and fixed it by deleting the .suo file for the solution.
I seem to also get different exceptions when toggling the Break when Common Language Runtime Exception is thrown setting, which is stored in the suo file (Debug Menu -> Exceptions)

The problem is your stub method. By using only .Return() it will give this value back only once. If you don't care about how many times the stub should return the value you should use .Return().Repeat.Any().

Related

App Resources breaking in unit tests, due to uncontrollable shadow copying from ReSharper

Background:
On an application I am working on, I am writing tests using a mixture of Visual Studio 2015, SpecFlow, and ReSharper 2016.3 (I'll abbreviate this as R#, because I'm lazy.)
The application I am working on sends HTML-formatted emails, based on a template, which are stored in HTML files that are set as Copy Always in Visual Studio 2015.
Problem:
When I attempt to run my tests, I get the following exception:
System.IO.DirectoryNotFoundException: Could not find a part of the path 'C:\Users\[Me]\AppData\Local\JetBrains\Installations\ReSharperPlatformVs14_001\Resources\SomeEmailTemplate.html`
The directory was not the output directory of the project I am working on, so I double-checked my R# settings, and confirmed that Shadow Copy was turned off. To be perfectly clear, my R# Shadow Copy checkbox is indeed unchecked.
The offending code is really pretty simple. Normal remedies like TestContext.CurrentContext.TestDirectory is not something I can, should, or even want to do, due to the fact that this code is needed by the application itself. It would be in appropriate to put test framework code in the application under test.
public class HtmlTemplateLog : ISectionedLog, IRenderableLog
{
#region Variables / Properties
private readonly string _rawHtml;
private readonly Dictionary<string, StringBuilder> _sectionDictionary = new Dictionary<string, StringBuilder>();
private StringBuilder _workingSection;
#endregion Variables / Properties
#region Constructor
public HtmlTemplateLog(string templateFile)
{
// This is specifically what breaks the tests.
_rawHtml = File.ReadAllText(templateFile)
.Replace("\r\n", string.Empty); // Replace all newlines with empty strings.
}
#endregion Constructor
#region Methods
// Methods work with the section dictionary.
// The RenderLog method does a string.Replace on all section names in the HTML.
// These methods aren't important for the question.
#endregion Methods
This is invoked as in the example below:
_someLog = new HtmlTemplateLog("Resources/SomeEmailTemplate.html");
// ...code...
_someLog.WriteLineInSection("{someSection}", "This is a message!");
string finalHtml = _someLog.RenderLog();
Questions:
1. I've turned off Shadow Copy on my R# tests. Why is this still doing Shadow Copies?
2. In what ways can I work around the fact that R# is not respecting the Shadow Copy checkbox, given that this is not test code, and thus that remedies that would normally be appropriate for test code aren't for this case?
I've discovered an answer for #2...though, it's rather clunky. I was inspired by the answer from #mcdon for a less-detailed version of the question.
Pretty much, if I don't want to resort to TestContext.CurrentContext.TestDirectory, then I need to make my local filenames into absolute paths. Unfortunately, R#'s broken Shadow Copy setting creates more work, since I can't just interrogate the currently-executing assembly - it will tell me the wrong thing. I need to get at the codebase instead and interrogate that.
I'm still a bit worried about what this code when we try to run it on the build server, however - I'm expecting 'unexpected' results. In that light, I'm wondering if the unexpected results can truly be called unexpected, given that I'm expecting that this won't work...
Anyways, the fix I came up with was this field-property system:
private string _presentWorkingDirectory;
private string PresentWorkingDirectory
{
get
{
if (!string.IsNullOrEmpty(_presentWorkingDirectory))
return _presentWorkingDirectory;
var assembly = Assembly.GetExecutingAssembly();
var codebase = new Uri(assembly.CodeBase);
var filePath = codebase.LocalPath;
var path = Directory.GetParent(filePath);
_presentWorkingDirectory = path.ToString();
return _presentWorkingDirectory;
}
}

Application changes not taking effect

I have made a change to a method used in a Functiod in a mapping file but it seems the new code is not taking effect, ever.
I have deployed properly, started the application, restarted related host instance (actually all host instances I could find) and still, the old code seems to execute.
Here's the, simple, method:
public string RemoveNonNumericChars(string stIn, int maxLength)
{
string strOut;
try
{
strOut = Regex.Replace(stIn, "[^0-9]", "");
System.Diagnostics.EventLog.WriteEntry("BizTalk Server 2009", strOut);
return strOut.Substring(0, maxLength);
}
catch
{
return string.Empty;
}
}
I added the writing to EventLog line to see that this code is indeed being executed, but I don't get anything in "Application" event logs.
I do NOT get an empty string being returned, so it really does seem like the old code that's being executed prior to me fixing the method.
What am I missing exactly ?
Thank you.
For some reason, the script is not able to correctly retrieve the Build Config selected in Visual Studio, it's taken from Debug when I'm actually trying to build it for a Test environment. I should have known, thanks anyways.

NUnit get results programmatically during run session

again i am trying to do something and not sure if it is possible. i want to run my Nunit tests and after each test is run, i want to output the result to my ui. the ui is custom and is used by my test team to run and see test results. when i say it is used, it is not developed yet (fully) :) - bringing me to this question.
my code so far
TestPackage package = new TestPackage(path);
RemoteTestRunner remote = new RemoteTestRunner();
remote.Load(package);
TestResult result = remote.Run(new NullListener(), TestFilter.Empty, true, LoggingThreshold.All);
while (remote.Running)
{
// want to capture results here
if (result.HasResults)
// i can never get here while test is running
}
How about dumping the results as XML into shared location. And then your UI can parse/pick up from that location
Also try to use common XML schema so that you can easily serialize/deserialize back from XML to C# object and vice versa
We have done smth similar in the past and above scenario has worked quite well

NUnit is not failing test with dynamic keyword of .Net 4.0

I am using NUnit with Visual Studio Express Edition 2010 for C#, Now, normally test works fine. But whenever I try to use Massive.cs, which is open source api to access database. Test fails from that file only. Now, if I run the application, api is working fine. I have created a different library file to access data base.
I seriously don't understand the error. It is just giving error that object reference is not set to an object. But if I run the code, it works fine. I am using dynamic keyword as shown in link of api above. Does that making problem with NUnit ?
Is there any other way to test in this type of Scenarios?
Here are the further details of the code,
Test class is like this
dynamic item = new Item();
item.Insert(new { Name = "Maggi", Description = "Its 2 Min Nuddles", IsDelete = false });
var items = item.All();
Assert.AreEqual("Maggi", items.FirstOrDefault().Name);
Now, I have put test here. Which gives error like shown in image,
Now if I run code in console application, then code is working fine, code snippet is given below
dynamic item = new Item();
item.Insert(new { Name = "Maggi", Description = "Its 2 Min Nuddles", IsDelete = false });
var result = item.All();
foreach (var i in result)
{
Console.WriteLine(i.Name + i.Description);
}
Console.Read();
Here, code is working and same thing is not working with NUnit Test. Please have a look and help me out. Please let me know if any further information is needed from my side.
Most probable explanation is that you haven't set up your connection string in the test project.
If you are using NUnit, just put it in app.config of your test project.
Solved... There is a issue with NUnit Testing. It was not taking config file pefectly. So, I made two changes. Changes I have done in Project setting.
First change is to change Application Base to bin\debug just give application base as this and then config file to .config to .exe.config and things are up and running. :)

How to the see output from unit-tests in the Test-Result window in VS2010?

I'm new to unit testing and I want to see output from my tests.
Let's assume I'm testing for the existance of certain objects:
List<MyObject> actual = target.GetMyObjects();
Assert.IsTrue(actual.Count > 0, String.Format("{0} objectes fetched", actual.Count));
In the 'Test Result' window in VS2010 I want to see the result of "String.Format("{0} objectes fetched", actual.Count)".
Is that possible?
Found it:
I added the column Output(StdOut) to the Test Result window.
I changed the end of my test method to this:
bool success = actual.Count > 0;
Assert.IsTrue(success, "No models in the database");
if (success)
{
Console.Write(String.Format("{0} models fetched", actual.Count));
}
Yes this is possible. If the test fails whatever message that you put in the second parameter might be useful.In your case if the count value is important for you to debug the error go ahead with it.
Even if the failing or succeeding the test is automated later when debugging this information might be helpful. http://www.creatingsoftware.net/2010/03/best-practices-for-assert-statements-in.html
Alternatively you could use
Debug.Print("whatever");
And then when you run your test, you get a hyperlink "Output" in the success/fail window which will show all of your debug messages.
Obviously you need to add
Using System.Diagnostics;
Dom
No, you don't want to see the output.
Each unit test must either succeed or fail. This enables the test runner to aggregate the test results into a single Fail/Pass test result. If human inspection is required, the point of unit testing is lost - it must be automated.

Categories

Resources