Showing posts with label Unit Tests. Show all posts
Showing posts with label Unit Tests. Show all posts

Saturday, 13 October 2012

Tolerance and the Equal constraint in NUnit tests

Those pesky tests that fail every once and a while because something took slightly longer than usual. Sure you could just run them again and they probably pass a second time round. There is another simple way to avoid this, the NUnit Within modifier for the Equal constraint.

[Test]
public void CreationDateTimeIsSetOnConstruction()
{
   var timeObject= new TimeClass();
   
   Assert.That(timeObject.CreationDateTime, Is.EqualTo(DateTime.Now)
         .Within(new TimeSpan(2000)));
}

Sunday, 12 June 2011

Visual Studio Breaking on Exceptions for MSTests

At home I don't have ReSharper installed (shock!) and I use MSTests (wtf?!) for some small old projects. Annoyingly VS would break on exceptions when running tests; given that these tests rely on exceptions being thrown it becomes a tad annoying.

Turns out I'm a massive idiot and I was just running the tests with the wrong keyboard shortcut - doh! Here are the shortcuts I was using and the ones I am now using:
  • Ctrl r + Ctrl t => Run tests in current context (debug mode)
  • Ctrl r + t => Run tests in current context
  • Ctrl r + Ctrl a => Run all tests in solution (debug mode)
  • Ctrl r + a => Run all tests in solution

Wednesday, 20 October 2010

Read an Embedded Resource Text File in C#

Here's a little snippet I use quite a lot in my test projects to read out an embedded resource text file as a string. The resourceName parameter is the full namespace of the resource, e.g. myproject.files.MyEmbeddedTextFile.txt

internal string GetFromResources(string resourceName)
{
    Assembly assem = this.GetType().Assembly;
    using (Stream stream = assem.GetManifestResourceStream(resourceName))
    {
        using (var reader = new StreamReader(stream))
        {
            return reader.ReadToEnd();
        }
    }
}

P.S. You may want to add some error handling to the above ;)

Friday, 18 June 2010

Mock ControllerContexts in ASP.Net MVC

After performing an upgrade to MVC 2 for a web application last week, I had a number of tests failing. This gave me an opportunity to refactor some controller tests and create a base class for my controller test classes. This new base class is straight forward and allows me to mock HttpRequestBase and HttpSessionStateBase easily on the mock ControllerContext - it also has an overload for mocking AJAX requests too. I expect this class to grow in time but it serves my needs for now:

public class TestController
{
 public static ControllerContext GetMockControllerContext()
 {
  return GetMockControllerContext("GET", false, null, null);
 }

 public static ControllerContext GetMockControllerContext(string httpMethod, bool isAjaxRequest)
 {
  return GetMockControllerContext(httpMethod, isAjaxRequest, null, null);
 }

 public static ControllerContext GetMockControllerContext(Mock httpRequestBase, Mock httpSessionStateBase)
 {
  return GetMockControllerContext("GET", false, httpRequestBase, httpSessionStateBase);
 }

 public static ControllerContext GetMockControllerContext(string httpMethod, bool isAjaxRequest, Mock httpRequestBase, Mock httpSessionStateBase)
 {
  var headerCollection = new NameValueCollection();

  // Add header value for ajax requests
  if (isAjaxRequest) headerCollection.Add("X-Requested-With", "XMLHttpRequest");

  if (httpRequestBase == null)
  {
   httpRequestBase = new Mock();
   httpRequestBase.Setup(r => r.HttpMethod).Returns(httpMethod);
   httpRequestBase.Setup(r => r.Headers).Returns(headerCollection);
   httpRequestBase.Setup(r => r.Form).Returns(new NameValueCollection());
   httpRequestBase.Setup(r => r.QueryString).Returns(new NameValueCollection());
  }

  if (httpSessionStateBase == null)
  {
   httpSessionStateBase = new Mock();
  }

  var mockHttpContext = new Mock();
  mockHttpContext.Setup(c => c.Request).Returns(httpRequestBase.Object);
  mockHttpContext.SetupGet(c => c.Session).Returns(httpSessionStateBase.Object);

  return new ControllerContext(mockHttpContext.Object, new RouteData(), new Mock().Object);
 }
}

Wednesday, 31 March 2010

Testing Private Methods in .Net

Some developers seem to be against testing private methods, that if you need to test private methods there is a design issue. I don't think I agree in all cases and extracting some method logic into another method for further testing seems valid to me. Having to make that method public (against it's design) just for testing purposes doesn't sit right, so I test private methods using the PrivateObject class found in the Visual Studio TestTools library...

[TestMethod]
public void IsValidInput_NumberString_ReturnsTrue()
{
 // Arrange 
 var myClass = new MyClassWithPrivateMethod();
 var privateObject = new PrivateObject(myClass);

 // Act
 bool result = (bool)privateObject.Invoke("IsValidInput", new object[] { "123" });

 // Assert
 Assert.IsTrue(result);
}