Why can't I create a callback for the List Find method in Moq? - entity-framework

I created an extension method that lets me treat a List as DbSet for testing purposes (actually, I found this idea in another question here on stack overflow, and it's been fairly useful). Coded as follows:
public static DbSet<T> AsDbSet<T>(this List<T> sourceList) where T : class
{
var queryable = sourceList.AsQueryable();
var mockDbSet = new Mock<DbSet<T>>();
mockDbSet.As<IQueryable<T>>().Setup(m => m.Provider).Returns(queryable.Provider);
mockDbSet.As<IQueryable<T>>().Setup(m => m.Expression).Returns(queryable.Expression);
mockDbSet.As<IQueryable<T>>().Setup(m => m.ElementType).Returns(queryable.ElementType);
mockDbSet.As<IQueryable<T>>().Setup(m => m.GetEnumerator()).Returns(queryable.GetEnumerator());
mockDbSet.Setup(d => d.Add(It.IsAny<T>())).Callback<T>(sourceList.Add);
mockDbSet.Setup(d => d.Find(It.IsAny<object[]>())).Callback(sourceList.Find);
return mockDbSet.Object;
}
I had been using Add for awhile, and that works perfectly. However, when I try to add the callback for Find, I get a compiler error saying that it can't convert a method group to an action. Why is sourceList.Add an Action, but sourceList.Find is a method group?
I'll admit I'm not particularly familiar with C# delegates, so it's likely I'm missing something very obvious. Thanks in advance.

The reason Add works is because the List<T>.Add method group contains a single method which takes a single argument of type T and returns void. This method has the same signature as an Action<T> which is one of the overloads of the Callback method (the one with a single generic type parameter, Callback<T>), therefore the List<T>.Add method group can be converted to an Action<T>.
With Find, you are trying to call the Callback method (as opposed to Callback<T>) which expects an Action parameter (as opposed to Action<T>). The difference here is that an Action does not take any parameters, but an Action<T> takes a single parameter of type T. The List<T>.Find method group cannot be converted to an Action because all the Find methods (there is only one anyway) take input parameters.
The following will compile:
public static DbSet<T> AsDbSet<T>(this List<T> sourceList) where T : class
{
var mockDbSet = new Mock<DbSet<T>>();
mockDbSet.Setup(d => d.Find(It.IsAny<object[]>())).Callback<Predicate<T>>(t => sourceList.Find(t));
return mockDbSet.Object;
}
Note that I have called .Callback<Predicate<T>> because the List<T>.Find method expects and argument of type Predicate. Also note I have had to write t => sourceList.Find(t) instead of sourceList.Find because Find returns a value (which means it doesn't match the signature of Action<Predicate<T>>). By writing it as a lambda expression the return value will be thrown away.
Note that although this compiles it will not actually work because the DbSet.Find method actually takes an object[] for it's parameter, not a Predicate<T>, so you will likely have to do something like this:
public static DbSet<T> AsDbSet<T>(this List<T> sourceList) where T : class
{
var mockDbSet = new Mock<DbSet<T>>();
mockDbSet.Setup(d => d.Find(It.IsAny<object[]>())).Callback<object[]>(keyValues => sourceList.Find(keyValues.Contains));
return mockDbSet.Object;
}
This last point has more to do with how to use the Moq library that how to use method groups, delegates and lambdas - there is all sorts of syntactic sugar going on with this line which is hiding what is actually relevant to the compiler and what isn't.

Related

not able to use DISTINCT or group by keyword in codeigniter

This is my controller.php:
$courserecord = $this->front->get_data_wheree('tbl_course_offered.course_id',array('isactive'=>'1'));
This is my Model.php:
function get_data_wheree($table,$where)
{
return $this->db->group_by($table,$where)->result();
}
In my model.php I want to use DISTINCT OR GROUP_BY in the Query.
The group_by is not working properly.
Your model is not working because the result() method is a member of the class CI_DB_result but group_by() returns an instance of CI_DB_query_builder. In other words, you are trying to call a method that does not exist for the class being used.
The methods get() and get_where() are the only two Query Builder methods that return a CI_DB_result object. Put simply, you have to call get() or get_where() before you can use result() or any similar methods.
The other problem is that group_by() does not take a second argument of the type you provide. You're providing an array but it expects a boolean. You need to add another method to define a where condition.
Your model's method should look like the following.
I changed the name of the first argument to better describe its purpose.
function get_data_where($groupby, $where)
{
return $this->db
->group_by($groupby)
->where($where)
->get('tbl_course_offered')
->result();
}

Why do I get a lambda error that no-one else gets?

I'm trying to debug the following line:
MOrigValue.AllInstances.TestString = () => "New value";
There's a red squiggly line under:
() => "New value";
Mouseover shows the following error:
Delegate 'Microsoft.Moles.Framework.MolesDelegates.Func<OrigValueP.OrigValue, string>' does not take 0 arguments
Here is the complete class:
namespace OrigValueP
{
public class OrigValue
{
public string TestString() { return "Original value"; }
}
}
Here's the info from the object browser.
Click on the property MOrigValue.AllInstances.TestString:
public static Microsoft.Moles.Framework.MolesDelegates.Func<OrigValueP.OrigValue,string> TestString { set; }
Member of OrigValueP.Moles.MOrigValue.AllInstances
So, to a non-techie like me, that would explain the red squiggly line error above..
Click on the property MOrigValue..TestString:
public Microsoft.Moles.Framework.MolesDelegates.Func<string> TestString { set; }
Member of OrigValueP.Moles.MOrigValue
To me, this looks like the definition that I would have expected to see for MOrigValue.AllInstances.TestString. In other words a property that is actually a Moled "method" that has no parameters and returns a string.
As an experiment, based on the first object browser info above, I inserted the class as an input parameter, as follows:
MOrigValue.AllInstances.TestString = (OrigValue) => "New value";
This works :)
But my workaround looks like a "hack". I've seen every page on the internet (including StackOverflow) relating to moles and how to remove them painlessly. Many of them have lines with a lambda similar to the following:
MMyClass.AllInstances.DoSomething = () => "Hello world";
Assert.AreEqual("Hello world", new MyClass().DoSomething());
The fundamental issue is that Moles started from a method that takes no parameters and returns a string. The Moled equivalent takes its own class as a parameter and returns a string. Surely Moles knows that TestString() is a member of OrigValue.
Maybe my problem is a result of using VS Express, rather than the paid versions. I can live with that, but it would still be interesting to know why I need the hack. There might be cases where the hack produces incorrect test results without my knowledge.
BTW: I think this example proves the value of the object browser.
Your expectation is wrong. The "hack" you describe is the official documented way to use the AllInstances nested type. Its delegates really do always take a parameter containing an instance of the type under test.
It is unlikely that you could have seen this form of usage of AllInstances
MMyClass.AllInstances.DoSomething = () => "Hello world";
which, if you have, could be a mistake made by the author of the code.
What you expect to be the definition of a delegate belonging to the AllInstances type is really a different kind of use of Moles: it's used to detour an instance method of a single instance.
The "Mole Basics" section of the document "Microsoft Moles Reference Manual" contains more information on the topic. Here is an excerpt from there.
Instance Methods (for One Instance)
... The properties to set up those moles are instance methods of the mole type itself. Each instantiated mole type is also associated with a raw instance of a moled method type.
For example, given a class MyClass with an instance method MyMethod:
public class MyClass {
public int MyMethod() {
...
}
}
We can set up two mole types of MyMethod such that the first one always returns 5 and the second always returns 10:
var myClass1 = new MMyClass() { MyMethod = () => 5 };
var myClass2 = new MMyClass() { MyMethod = () => 10 };

Why is param in this lambda expression?

The MSDN magazine article by Josh Smith on MVVM contains a lambda expression I don't completely understand. What is the purpose of param in this code?
_saveCommand = new RelayCommand(param => this.Save(),
param => this.CanSave );
Translated to my preferred language VB it's:
Dim saveAction as New Action(Of Object)(AddressOf Me.Save)
_saveCommand = New RelayCommand(saveAction, Function(param) Me.CanSave)
I would have expected to only see param if it is used within CanSave or Save. I am somewhat new to lambda expressions. It's odd for me to see a variable that is neither declared nor used anywhere as far as I can tell. Any explanation would be appreciated.
To put this in context the constructor for RelayCommand (C#) is:
public RelayCommand(Action<object> execute, Predicate<object> canExecute)
and in VB:
Public Sub New(ByVal execute As Action(Of Object), _
ByVal canExecute As Predicate(Of Object))
The lambda expression is declaring it - the place where it appears is basically a declaration. If it didn't, it wouldn't be compatible with Action(Of Object). That's why it's there - even though you don't actually need the value.
With anonymous methods, if you don't need any parameter values you can omit the parameter list entirely:
_saveCommand = new RelayCommand(delegate { this.Save(); },
delegate { return this.CanSave; });
... but you can't do that with lambda expressions. You have to specify the parameter list - either just as a parameter name for a single parameter, or a full list in brackets. The code you've presented is equivalent to:
_saveCommand = new RelayCommand((Object param) => this.Save(),
(Object param) => this.CanSave);

Need help understanding Generics, How To Abstract Types Question

I could use some really good links that explain Generics and how to use them. But I also have a very specific question, relater to working on a current project.
Given this class constructor:
public class SecuredDomainViewModel<TDomainContext, TEntity> : DomainViewModel<TDomainContext, TEntity>
where TDomainContext : DomainContext, new()
where TEntity : Entity, new()
public SecuredDomainViewModel(TDomainContext domainContext, ProtectedItem protectedItem)
: base(domainContext)
{
this.protectedItem = protectedItem;
}
And its creation this way:
DomainViewModel d;
d = new SecuredDomainViewModel<MyContext, MyEntityType>(this.context, selectedProtectedItem);
Assuming I have 20 different EntityTypes within MyContext, is there any easier way to call the constructor without a large switch statement?
Also, since d is DomainViewModel and I later need to access methods from SecuredDomainViewModel, it seems I need to do this:
if (((SecuredDomainViewModel<MyContext, MyEntityType>)d).CanEditEntity)
But again "MyEntityType" could actually be one of 20 diffent types. Is there anyway to write these types of statements where MyEntityType is returned from some sort of Reflection?
Additional Info for Clarification:
I will investigate ConstructorInfo, but I think I may have incorrectly described what I'm looking to do.
Assume I have the DomainViewModel, d in my original posting.
This may have been constructed via three possible ways:
d = new SecuredDomainViewModel<MyContext, Order>(this.context, selectedProtectedItem);
d = new SecuredDomainViewModel<MyContext, Invoice>(this.context, selectedProtectedItem);
d = new SecuredDomainViewModel<MyContext, Consumer>(this.context, selectedProtectedItem);
Later, I need to access methods on the SecuredDomainViewModel, which currently must be called this way:
ex: if (((SecuredDomainViewModel<MyContext, Order)d).CanEditEntity)
ex: if (((SecuredDomainViewModel<MyContext, Invoice)d).CanEditEntity)
ex: if (((SecuredDomainViewModel<MyContext, Consumer)d).CanEditEntity)
Assuming I have N+ entity types in this context, what I was hoping to be able to do is
something like this with one call:
ex: if (((SecuredDomainViewModel<MyContext, CurrentEntityType)d).CanEditEntity)
Where CurrentEntityType was some sort of function or other type of call that returned Order, Invoice or Consumer based on the current item entity type.
Is that possible?
You can create a non-generic interface that has the CanEditEntity property on it, make SecuredDomainViewModel inherit off that, then call the property through the interface...
Also, the new() constructor allows you to call a constructor on a generic type that has no arguments (so you can just write new TEntity()), but if you want to call a constructor that has parameters one handy trick I use is to pass it in as a delegate:
public void Method<T>(Func<string, bool, T> ctor) {
// ...
T newobj = ctor("foo", true);
// ...
}
//called later...
Method((s, b) => new MyClass(s, b));
I can't help on the links, and likely not on the type either.
Constructor
If you have the Type, you can get the constructor:
ConstructorInfo construtor = typeof(MyEntityType).GetConstructor(new object[]{TDomainContext, ProtectedItem});
Type
I'm not really sure what you're looking for, but I can only see something like
if (((SecuredDomainViewModel<MyContext, entityType>)d).CanEditEntity)
{
entityType=typeof(Orders)
}
being what you want.

How do I mock a Where clause in EF4

I am re-writing this question to make it clearer what I need to do. I am trying to use Rhino-Mock to test:
public IQueryable<TxRxMode> GetAllModes()
{
return m_context.TxRxModes.Where(txRxMode => txRxMode.Active);
}
Here's the code:
var context = MockRepository.GenerateStub<IProjectContext>();
//Returns an empty list
context.Expect(c => c.TxRxModes.Where(Arg<Func<TxRxMode, bool>>.Is.Anything)).Return(new List<TxRxMode>().AsQueryable());
TxRxModes in an IObjectSet property on the context and I want it to return an empty IQueryable<TxRxMode> object when the return m_context.TxRxModes.Where(txRxMode => txRxMode.Active); code is called.
When I run this, the Expect method call throws the an ArgumentNullException:
Value cannot be null.
Parameter name: predicate
I have tried the simpler:
IObjectSet<TxRxMode> modes = MockRepository.GenerateStub<IObjectSet<TxRxMode>>();
context.Expect(c => c.TxRxModes).Return(modes);
but this throws a null reference exception when I call
return m_context.TxRxModes.Where(txRxMode => txRxMode.Active);
Basically, this is part of the method I am trying to mock, so the key question is how do I mock this Where statement?
Where is actually a global static method and you shouldn't be mocking it. It operates on an IEnumerable however and you could just mock that.
Its kind of a hassle doing it with rhino mocks however. I would recommend doing the mock manually (if you need to do it at all).