views:

166

answers:

3

Hi,

I'm trying to create a mock HttpContextBase for unit test.

var fakePrinciple = new GenericPrincipal(
           new GenericIdentity(userId), 
           rolesList.ToArray());            
var mockHttpContext = new Mock<HttpContextBase>();
mockHttpContext.Setup(t => t.User).Returns(fakePrinciple);
HttpContextBase mockedContext = mockHttpContext.Object;

The unit test fails at the last statement with

threw exception: System.ArgumentException: Unable to obtain public key for StrongNameKeyPair..

System.Reflection.StrongNameKeyPair.nGetPublicKey(Boolean exported, Byte[] array, String container) System.Reflection.StrongNameKeyPair.get_PublicKey() System.AppDomain.InternalDefineDynamicAssembly(AssemblyName name, AssemblyBuilderAccess access, String dir, Evidence evidence, PermissionSet requiredPermissions, PermissionSet optionalPermissions, PermissionSet refusedPermissions, StackCrawlMark& stackMark, IEnumerable`1 unsafeAssemblyAttributes) System.AppDomain.DefineDynamicAssembly(AssemblyName name, AssemblyBuilderAccess access) Castle.DynamicProxy.ModuleScope.CreateModule(Boolean signStrongName) Castle.DynamicProxy.ModuleScope.ObtainDynamicModuleWithStrongName() Castle.DynamicProxy.ModuleScope.ObtainDynamicModule(Boolean isStrongNamed) Castle.DynamicProxy.Generators.Emitters.ClassEmitter.CreateTypeBuilder(ModuleScope modulescope, String name, Type (blah blah snip)

I googled and the suggestions here don't seem to work (change RSA folder security setting etc) http://groups.google.com.br/group/castle-project-users/browse_thread/thread/85685cf32a795158

Am I correct to think that because HttpContextBase is part of System.Web.Abstraction, which is a signed assembly. Moq will actually attempt to sign the dynamic assembly, and fail?

A: 

Check out this blog post by Scott Hanselman - it's a little old, but the MvcMockHelpers he displays there will probably give you a good idea of how to accomplish what you're doing.

Tomas Lycken
A: 

Hi, You should watch the this video on asp.net site that is showing an amazing example of implemention.

lakhlaniprashant.blogspot.com
Signing is the issue here, not how to mock in mvc.
Will
ok agreed my mistake
lakhlaniprashant.blogspot.com
+3  A: 

MoQ uses Castle DynamicProxy for generating mocks at runtime. Rhino Mocks uses the same library for the same purpose. If you check here:

http://ayende.com/Blog/archive/2006/06/09/UnableToObtainPublicKeyForStrongNameKeyPair.aspx

you'll see that the issue is one of permissions to the machine key store. Whatever user account is running the test must have permission to create and delete keys in the store.

You can find much more details about this issue here: http://groups.google.co.uk/group/RhinoMocks/browse_thread/thread/26df68ff01567509/5ddebf407228edc4

Will
I checked the permissions on RSA and Crypto folders but somehow it is not set for Machine Keys. Thanks Will.
rokeyge