Can not instantiate proxy...Could not find a parameterless constructor - mongodb

I am trying to create a unit test using Moq which tests the MongoDB.AspNet.Identity V2 provider. This line is giving me grief:
var appUser = new Mock<PreRegistrationMVC.Models.ApplicationUser>();
var userStore = new Mock<MongoDB.AspNet.Identity.UserStore<PreRegistrationMVC.Models.ApplicationUser>>();
It seems the userStore won't instantiate properly here is the error.
Castle.DynamicProxy.InvalidProxyConstructorArgumentsException was unhandled by user code
HResult=-2147024809
Message=Can not instantiate proxy of class: MongoDB.AspNet.Identity.UserStore`1[[MVC.Models.ApplicationUser, MVC, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null]].
Could not find a parameterless constructor.
Source=Moq
StackTrace:
at Castle.DynamicProxy.ProxyGenerator.CreateClassProxyInstance(Type proxyType, List`1 proxyArguments, Type classToProxy, Object[] constructorArguments)
at Castle.DynamicProxy.ProxyGenerator.CreateClassProxy(Type classToProxy, Type[] additionalInterfacesToProxy, ProxyGenerationOptions options, Object[] constructorArguments, IInterceptor[] interceptors)
at Moq.Proxy.CastleProxyFactory.CreateProxy(Type mockType, ICallInterceptor interceptor, Type[] interfaces, Object[] arguments)
at Moq.Mock`1.<InitializeInstance>b__2()
at Moq.PexProtector.Invoke(Action action)
at Moq.Mock`1.InitializeInstance()
at Moq.Mock`1.OnGetObject()
at Moq.Mock.GetObject()
at Moq.Mock.get_Object()
at Moq.Mock`1.get_Object()
at MVC_Tests.Identity.Accounts.AccountController_Test.TestSuccessfulRegister() in c:\Users\Tim\Documents\Visual Studio 2013\Projects\PreRegistrationApp\MVC_Tests\Identity\Accounts\AccountController_Test.cs:line 108
InnerException:
I am completely new to Moq so I am looking for:
What type of settings are needed for Moq to instantiate this? Is there something about the UserStore class that won't play well with Moq?
Thanks for reading.

MOQ is good for mocking interfaces, but does not work so well with concrete classes. So instead of mocking concrete class, ask for the inteface:
var userStore = new Mock<IUserStore<PreRegistrationMVC.Models.ApplicationUser>>();
Also ApplicationUser should be POCO, so no need to mock it, just create its instance without MOQ and use in tests.

You can try referring Mock behavior,as shown below
Mock<testClass>(MockBehavior.Strict, new object[] {"Hello"});

I had this problem. I had written...
var x = new Mock<Concrete>();
... instead of ...
var x = new Mock<IConcrete>();

I know this is a late response, but I was looking for an answer and couldn't find exactly what I needed, but when creating a mock, you can pass the parameters to your wanted constructor.
So for example if you have class like this:
public class Foo
{
private readonly Boo _boo;
public Foo(Boo boo)
{
_boo = boo;
}
}
You can mock it like this:
private readonly Mock<Foo> _foo = new Mock<Foo>(new Mock<Boo>().Object);

Add an empty constructor to your ApplicationUser class.

Related

Entity Framework: DbContext and setting the ProviderName

When you derive from DbContext and use the parameter-less constructor it will load a connection string from web.config. You also have the option of explicitly specifying the connectionString using one of the other DbContext constructors.
My particular situation dictates that the connection string CANNOT be specified in the web.config, as the location of the server/username and password are determined at runtime. Easy fix right? Just use the above mentioned constructor to specify the connection string? Wrong.
The problem is that when you specify the connection string using said constructor, it still attempts to use the default provider, so if you're using one or more non standard providers, as I am, it will not work.
I'm sure I can change the default provider in the web.config, but I want to use multiple providers so this will not do.
The only possible way around this that I can see is to use ObjectContext instead of DbContext, which seems to allow you to specify the provider along with the database connection string.
Is there any other way to do it? Is my workaround fairly reasonable?
I believe I can also create a DbContext from an ObjectContext instance.
Create your DbConnection manually and pass it to the DbContext constructor as follows:
var conn = DbProviderFactories.GetFactory("MY_CONN_PROVIDER").CreateConnection();
conn.ConnectionString = "MY_CONN_STR";
new DbContext(conn, true);
Notice the second parameter bool contextOwnsConnection is true. Since you don't re-use the connection elsewhere, it lets the context manage the connection and Dispose() it when needed.
You can get to the ObjectContext through IObjectContextAdapter:
((IObjectContextAdapter)context).ObjectContext
DbContext ("context" above) still wraps ObjectContext, so don't worry that you will have a new instance.
You can instantiate DbContext using this overload
public DbContext(ObjectContext objectContext, bool dbContextOwnsObjectContext) {}
for example:
public class YourDbContext : DbContext
{
public YourDbContext() : this(new YourObjectEntities(), dbContextOwnsObjectContext: true)
{}
}
Then you can set your connection string inside of YourObjectEntities:
public partial class YourObjectEntities : ObjectContext
{
public const string ConnectionString = "name=YourEntities"; // Get it from somewhere
public YourObjectEntities() : base(ConnectionString, "YourEntities")
{
// Some initialization, e.g. ContextOptions.LazyLoadingEnabled = false;
}
}
How you specify the provider there is your exercise.
Try like this ,
public DBDataContext _dataContex;
public DBDataContext DBContext
{
get
{
if (_dataContex== null)
{
_v= new DBDataContext(ConfigurationManager.ConnectionStrings["yourConnectinString"].ConnectionString);
}
return _dataContex;
}
}

DataContractSerializer. Serializing class through interface

I have class that implements some interface:
[DataContract]
public class ScriptState : IScriptState
{
<...>
}
I have simple helper class
public class Serializer
{
string Serialize<T>(T obj)
{
MemoryStream ms = new MemoryStream();
DataContractSerializer ser = new DataContractSerializer(typeof(T));
ser.WriteObject(ms, obj);
<...>
}
}
the problem is that I have loose coupled application and I get ScriptState object something like this:
IScriptstate ss = ServiceLocator.Resolve<IScriptState>();
i.e. variable has type of interface, and it is being processed by serializer:
Serializer.Serialize(ss);
and because of this DataContracrSerializer is instantiated with type of interface IScriptState, but real type of object is ScriptState, which leads to error, that type ScriptState is not expected.
Standard workaround should be adding knowntype ScriptState to interface IScriptState, but I can't do this obviously:
[KnownType(typeof(Scriptstate))]
IScriptState
{}
because assembly with interface has no reference to assembly with class.
Is there another solution??
I think I've found solution. In helper class use obj.GetType() instead of typeof(T) :
DataContractSerializer ser = new DataContractSerializer(obj.GetType());

Reflection / C# typing errors when publishing an F# class implementing an interface

I have an interface written in C#, but when implementing it in F#, I noticed some oddities.
The F# class has to be cast to the interface before C# can consume it
After casting, WPF can't read it's properties (Bindings failed and SNOOP was unable to reflect on it)
I can wrap the object in C# code and everything works fine.
the interface
public interface IInterpret {
public string Name {get;}
public IEnumberable<Project> Interpret(string text);
}
The F# Class
type Interpreter()=
interface IInterpret with
member x.Name = "FParsec Based"
member x.Interpret(str) = Seq.empty
The code below fails to compile
The error is about Interpreter not implementing IInterpert
public ViewModel(){
IInterpret i = new FSharpLib.Interperter();
}
This is my current workaround
public class MyProxy: IInterpret{
private IInterpret _cover;
public MyProxy() {
_cover = new FSharpLib.Interperter() as IInterpret;
}
public string Name { get { return _cover.Name; } }
public IEnumerable<Project> Interpret(string text){
return _cover.Interpret(text);
}
}
Is there something I'm doing wrong with my F# class def, or is the proxy needed? I'm using the current VS2010 f#, not an out of band drop.
F# implements all interfaces explicitly. This means you must explicitly cast to the interface type.
I don't know a ton about WPF binding to explicit interfaces, but see if these
http://leecampbell.blogspot.com/2008/09/generic-binding-in-wpf-through-explicit.html
http://social.msdn.microsoft.com/Forums/en-US/wpf/thread/92a2a3ba-74a6-4c79-9c75-f42d232a4dbf
help? (I just found them Bing-ing for "wpf binding explicit interfaces".)
(Another alternative may be to do something like
type Interpreter()=
member x.Name = "FParsec Based"
member x.Interpret(str:string) = Seq.empty
interface IInterpret with
member x.Name = x.Name
member x.Interpret(str) = x.Interpret(str)
where you "explicitly implement the interface implicitly", if you pardon the confusing terminology.)

Entity Framework 4, MOQ,

I am using EF4, Microsoft.Entity.CTP, and the latest MOQ. I am trying to create a generic repository class and moq the DBContext using MOQ. Whenever I run my moq test I get "object reference not set to an instance of an object" on this.context.Set().Add(entity); and I don't understand why. The code runs ok without a moq.
public class GenericRepository<TEntity> : IGenericRepository<TEntity> where TEntity : class
{
private IContext context;
public GenericRepository(IContext context)
{
this.context = context;
}
public IList<TEntity> List
{
get { return context.Set<TEntity>().ToList(); }
}
public void Create(TEntity entity)
{
this.context.Set<TEntity>().Add(entity);
this.context.SaveChanges();
}
}
var mock = new Mock<IContext>();
GenericRepository<Product> producRepository = new GenericRepository<Product>(mock.Object);
mock.Setup(x => x.Product.Add(productType));
mock.Setup(x => x.SaveChanges());
productRepository.Create(product);
mock.VerifyAll();
You need to mock out the list implementation behind Set. I'm not at the compute ATM but iirc it's an IDbSet.
Change your code first definitions from DbSet to IDbSet and then you can mock them.
http://blogs.msdn.com/b/efdesign/archive/2010/06/21/productivity-improvements-for-the-entity-framework.aspx
I am considering changing my DbContext.tt file to generate IDbSet instead of DbSet, but only after I get the mocking to work.
I am not saying this makes the rest of the work easy, but it will get you past one problem.
What I need help with is what to do after changing my code first definitions to be based on the EF DbContext interfaces. For example, I create instances of my DbSet objects and add them.
Mock<IPosManContext> posManContext;
posManContext.Object.Set(typeof(note_template));
posManContext.Object.note_template.Add(
new note_template()
{
note_template_id = 1,
act_flag = "Y",
desc_text = "Monday Monday",
last_update_dtm = now,
last_update_user_id = "hsimpson",
});
But I get an error that the DbSet is null.
Microsoft needs to provide a good example of what to do.
They went half the way by providing public interfaces for mocking, but I still need more help.
Joe

Using Moq with Windsor -- Object of Type Moq.Mock[IFoo] cannot be converted to IFoo

I'm trying to set up some Moq repositories to test my service with Castle Windsor as my IOC. Mu service depends on IFoo, so I'm creating a moq instance that implements IFoo and injecting it into the container like so:
_container.AddComponent("AutoBill",
typeof (AutoBillService), typeof (AutoBillService));
var mockUserRepository = new Mock<IUserRepository>();
var testUser = new User()
{
FirstName = "TestFirst",
LastName = "TestLast",
UID=1
};
mockUserRepository.Setup(repo => repo.GetUser(testUser.UID))
.Returns(testUser);
_container.Kernel.AddComponentInstance("UserRepository",
typeof(IUserRepository), mockUserRepository);
var service = _container.Resolve<AutoBillService>(); //FAIL
Doing this gives me an exception:
System.ArgumentException: Object of type 'Moq.Mock`1[IUserRepository]' cannot be converted to type 'IUserRepository'
Can anyone see what I'm doing wrong?
You should pass mockUserRepository.Object instead of mockUserRepository.
This would be a lot more evident if you used the strongly typed API:
_container.Register(Component
.For<IUserRepository>()
.Instance(mockUserRepository.Object));
This compiles because the Object property implements IUserRepository.
I head the same problem with Castle Windsor.
A dinamyc initialization with method:
container.Register(Component.For<IUserRepository>()
.Instance(mockUserRepository.Object));
didn't work until I removed from my caslteRepository.config file pre-initialized repositories (like your IUserRepository) and left container "empty" from repositories.