Thursday, May 7, 2015

Unit Testing Invalid Model State in a WebApi 2 Controller

I choose to do this operation in two different tests.
1. Test the controller behavior when the model state is invalid.  Do this by forcing the model state to invalid by adding an entry before the method is called.
2. Test the model state attributes independently from the controller.

For the controller Test

[TestMethod]
public void WhenModelStateIsInvalidDoNotSave()
{
  var mockRepo = new Mock<IProductRepo>();
  mockRepo.Setup(x=>x.Save(It.IsAny<Product>());

  var ctrl = new ProductController(mockRepo.Object);
  ctrl.ModelState.AddModelError("SomeRandomProperty","SomeRandomProperty was not valid");

  var actual = ctrl.Post(new Product());

  mockRepo.Verify(x=>x.Save(It.IsAny<int>()),Times.Never);
  Assert.IsInstanceOfType(actual, typeof(InvalidModelStateResult));
}


public IHttpActionResult Post([FromBody] Product model)
{
  if(!ModelState.IsValid)
    {
       return BadRequest(ModelState);
     }
   
   ProductRepo.Save(model);
    return Ok();
}

Wednesday, March 25, 2015

AngularJs Style Guide

Simple but radical concept, have the tests right next to the code.  In server side code, I'm so used to separating tests into a separate project. On some projects I work on the tests need to be stripped out for the production build, even thought unit tests should be harmless, but not my call.  This can be done with the build scripts, if needed.

There are many other gems in this document, check it out.
https://github.com/johnpapa/angular-styleguide#organizing-tests

Tuesday, March 10, 2015

Creating a self signed cert using makecert

http://www.jayway.com/2014/09/03/creating-self-signed-certificates-with-makecert-exe-for-development/

"C:\Program Files (x86)\Windows Kits\8.0\bin\x86\makecert.exe" ^
-n "CN=CARoot" ^
-r ^
-pe ^
-a sha512 ^
-len 4096 ^
-cy authority ^
-sv CARoot.pvk ^
CARoot.cer

"C:\Program Files (x86)\Windows Kits\8.0\bin\x86\pvk2pfx.exe" ^
-pvk CARoot.pvk ^
-spc CARoot.cer ^
-pfx CARoot.pfx ^
-po Test123

Wednesday, March 4, 2015

WebMatrix.data

My favorite quick data access tool is WebMatrix.Data.  It went through a name change, I'm posting it here so I don't forget it. 

http://www.nuget.org/packages/Microsoft.AspNet.WebPages.Data/