How to get PEX to automatically generate inputs for code involving LINQ - linq

I'm having trouble getting PEX to automatically cover methods calling Linq extension methods, such as Where() and Contains() in this example:
public class MyEntity
{
public int Id { get; set; }
}
public interface IWithQueryable
{
IQueryable<MyEntity> QueryableSet();
}
public class ConsumerOfIhaveIQueryable
{
private readonly IWithQueryable _withIQueryable;
public ConsumerOfIhaveIQueryable(IWithQueryable withIQueryable)
{
// <pex>
Contract.Requires<ArgumentNullException>(
withIQueryable != null, "withIQueryable");
// </pex>
_withIQueryable = withIQueryable;
}
public IEnumerable<MyEntity> GetEntitiesByIds(IEnumerable<int> ids)
{
Contract.Requires<ArgumentNullException>(ids != null, "ids");
// <pex>
Contract.Assert
(this._withIQueryable.QueryableSet() != (IQueryable<MyEntity>)null);
// </pex>
IEnumerable<MyEntity> entities =
_withIQueryable.QueryableSet().Where(
entity => ids.Contains(entity.Id));
if (entities.Count() != ids.Count())
{
return null;
}
return entities;
}
}
[PexClass(typeof(ConsumerOfIhaveIQueryable))]
[PexAllowedExceptionFromTypeUnderTest(typeof(InvalidOperationException))]
[PexAllowedExceptionFromTypeUnderTest(typeof(ArgumentException), AcceptExceptionSubtypes = true)]
[TestClass]
public partial class ConsumerOfIhaveIQueryableTest
{
[PexMethod]
public IEnumerable<MyEntity> GetEntitiesByIds(
[PexAssumeUnderTest]ConsumerOfIhaveIQueryable target,
int[] ids)
{
var result = target.GetEntitiesByIds(ids);
PexAssert.IsTrue(result.Count() == ids.Length);
return result;
}
}
When I'm running PEX exploration on this PexMethod I'm seeing the following problems:
I keep getting the same exception and PEX keeps suggesting the same "invariant" fix in the form of the Contract.Assert that you see in the // region:
I believe the problem is somehow related to how Pex relates to Linq but I'm not sure
--- Description
failing test: ArgumentNullException, Value cannot be null.
Parameter name: source
[TestMethod]
[PexGeneratedBy(typeof(ConsumerOfIhaveIQueryableTest))]
[PexRaisedException(typeof(ArgumentNullException))]
public void GetEntitiesByIdsThrowsArgumentNullException385()
{
using (PexChooseBehavedBehavior.Setup())
{
SIWithQueryable sIWithQueryable;
ConsumerOfIhaveIQueryable consumerOfIhaveIQueryable;
IEnumerable<MyEntity> iEnumerable;
sIWithQueryable = new SIWithQueryable();
consumerOfIhaveIQueryable =
ConsumerOfIhaveIQueryableFactory.Create((IWithQueryable)sIWithQueryable);
int[] ints = new int[0];
iEnumerable = this.GetEntitiesByIds(consumerOfIhaveIQueryable, ints);
}
}
--- Exception details
System.ArgumentNullException: Value cannot be null.
Parameter name: source at System.Linq.IQueryable'1 System.Linq.Queryable.Where(System.Linq.IQueryable'1 source, System.Linq.Expressions.Expression'1> predicate)
c:\users\moran\documents\visual studio 2010\Projects\PexTuts\PexIQueryable\PexIQueryable\ConsumerOfIhaveIQueryable.cs(29): at System.Collections.Generic.IEnumerable'1 PexIQueryable.ConsumerOfIhaveIQueryable.GetEntitiesByIds(System.Collections.Generic.IEnumerable`1 ids)
c:\users\moran\documents\visual studio 2010\Projects\PexTuts\PexIQueryable\PexIQueryable.Tests\ConsumerOfIhaveIQueryableTest.cs(34): at System.Collections.Generic.IEnumerable'1 PexIQueryable.ConsumerOfIhaveIQueryableTest.GetEntitiesByIds(PexIQueryable.ConsumerOfIhaveIQueryable target, System.Int32[] ids)
I can't get PEX to generate relevant inputs. As you can see, I tried to "help" it by adding a PexAssert and a branch in my code, but this branch is never covered, even though it should be relatively simple to generate a code that would walk that path. PEX only tries to pass null or an empty array as the list of Ids (I read somewhere that it is easier for PEX to work with arrays (int[]) rather than IEnumerable.
Would love to get some comments on this...
BTW, this is my first SO post, Hope I didn't spam with too much code and info.
Moran

After some time setting up the code for this, I've made a few assumptions. I'm assuming that you're stubbing the IWithQueryable via a Moles stub and also that the NullArgumentException occurs when you remove the Contract assertion that the QueryableSet() method doesn't return null.
As for the code, IMO the more code the better, as long as it's relevant- far better to have too much than too little to go on, so that's fine. As above, do try to make clear all the assumptions in the code (e.g. the Moles stubbing (as there's different ways to achieve this and it's something one has to assume).
I'm not 100% sure what you're asking. The code is failing because the stubbed IWithQueryable object doesn't have an implmementation for the QueryableSet() method and that method returns null. The PexAssert here won't help it figure out how to create a LINQ provider, which is what you're asking it to do. The PexChooseBehavedBehavior.Setup() simply replaces any calls to delegates on the Moles stubs (which don't have a custom delegate) with the default behaviour which is default(T), so that's why the source is null- the QueryableSet() is initialised to null.
You can solve this in a few ways (at least in the sense of providing a way of creating the QueryableSet() method). You can create a factory method to generate either the whole SIWithQueryable, or just the QueryableSet delegate. This is something that Pex suggests (however, with me it got the types and namespaces muddled-up). For instance:
/// <summary>A factory for Microsoft.Moles.Framework.MolesDelegates+Func`1[System.Linq.IQueryable`1[StackOverflow.Q9968801.MyEntity]] instances</summary>
public static partial class MolesDelegatesFactory
{
/// <summary>A factory for Microsoft.Moles.Framework.MolesDelegates+Func`1[System.Linq.IQueryable`1[StackOverflow.Q9968801.MyEntity]] instances</summary>
[PexFactoryMethod(typeof(MolesDelegates.Func<IQueryable<MyEntity>>))]
public static MolesDelegates.Func<IQueryable<MyEntity>> CreateFunc()
{
throw new InvalidOperationException();
// TODO: Edit factory method of Func`1<IQueryable`1<MyEntity>>
// This method should be able to configure the object in all possible ways.
// Add as many parameters as needed,
// and assign their values to each field by using the API.
}
/// <summary>A factory for Microsoft.Moles.Framework.MolesDelegates+Func`1[System.Linq.IQueryable`1[StackOverflow.Q9968801.MyEntity]] instances</summary>
[PexFactoryMethod(typeof(SIWithQueryable))]
public static SIWithQueryable Create()
{
var siWithQueryable = new SIWithQueryable();
siWithQueryable.QueryableSet = () => { throw new InvalidOperationException(); };
return siWithQueryable;
// TODO: Edit factory method of Func`1<IQueryable`1<MyEntity>>
// This method should be able to configure the object in all possible ways.
// Add as many parameters as needed,
// and assign their values to each field by using the API.
}
}
and then hook it up to the test method with one of the two lines assigning sIWithQueryable:
[TestMethod]
[PexGeneratedBy(typeof(ConsumerOfIhaveIQueryableTest))]
public void GetEntitiesByIdsThrowsArgumentNullException678()
{
SIWithQueryable sIWithQueryable;
// Either this for the whole object.
sIWithQueryable = MolesDelegatesFactory.Create();
// Or this for just that delegate.
sIWithQueryable = new SIWithQueryable();
sIWithQueryable.QueryableSet = MolesDelegatesFactory.CreateFunc();
ConsumerOfIhaveIQueryable consumerOfIhaveIQueryable;
IEnumerable<MyEntity> iEnumerable;
consumerOfIhaveIQueryable = ConsumerOfIhaveIQueryableFactory.Create((IWithQueryable) sIWithQueryable);
int[] ints = new int[0];
iEnumerable = this.GetEntitiesByIds(consumerOfIhaveIQueryable, ints);
}
This will then call your factory methods when creating the stub for IWithQueryable. This is still a problem, as regenerating the explorations will wipe out the stub setup.
If you provide the parameterless factory method to create the stub (MolesDelegatesFactory.CreateFunc()), then Pex will know about this and generate the tests to use it. So, it will correctly manage the behaviour across test regenerations. Unfortuantely, Pex suggests creating this delegate as a factory method- however, it is never called, the default implementation is always used, it seems one has to mock the parent type.
However, I'm wondering why you're creating an interface IWithQueryable that simple wraps another, and also, what you expect to do with the IQueryable. In order to do anything very useful, you'll have a lot of work going on to deal with the IQueryable interface - the Provider and Expression mainly, you'll pretty-much have to write a mock query provider, which will not be easy.

Related

Is it possible to pass null reference to Init view model?

I have this call on one view model
ShowViewModel<MyViewModel>(
new MyParams { ... }
);
On MyViewModel I have this Init method which works perfect
public void Init(MyParams params)
{
if (params != null)
{
// some logic
}
else
{
// some other logic
}
}
On another view model I have
ShowViewModel<MyViewModel>();
I expect to receive null on MyViewModel init method, instead of that I get an instance of 'MyParams'. That's generating problems since I have specific logic to handle the call with no parameters
I have custom presenter logic that might responsible for this, but at first sight I couldn't identify any custom logic as responsible. Is this the standard behavior for complex params?
Unfortunately, no there isn't a way to pass null using a parameters object.
The reason is that when Mvx creates the ViewModel and attempts to call the Init method, it will first convert your object instance into a simple dictionary (key/value pairs). If you use the no arg version, then it creates an empty dictionary. At this point, it creates an MvxBundle which includes the dictionary.
When Mvx is finally ready to call your Init method, it takes this dictionary and attempts to create an actual object.
It's this method that creates the instance to pass to Init.
MvxSimplePropertyDictionaryExtensionMethods.Read()
https://github.com/MvvmCross/MvvmCross/blob/8a824c797747f74716fc64c2fd0e8765c29b16ab/MvvmCross/Core/Core/Platform/MvxSimplePropertyDictionaryExtensionMethods.cs#L54-L72
public static object Read(this IDictionary<string, string> data, Type type)
{
var t = Activator.CreateInstance(type);
var propertyList =
type.GetProperties(BindingFlags.Instance | BindingFlags.Public | BindingFlags.FlattenHierarchy).Where(p => p.CanWrite);
foreach (var propertyInfo in propertyList)
{
string textValue;
if (!data.TryGetValue(propertyInfo.Name, out textValue))
continue;
var typedValue = MvxSingletonCache.Instance.Parser.ReadValue(textValue, propertyInfo.PropertyType,
propertyInfo.Name);
propertyInfo.SetValue(t, typedValue, new object[0]);
}
return t;
}
Notice how it calls Activator.CreateInstance(type) which will always return an instance.
So that is why you'll never get an null value in Init.
My recommendation is to simply add a property to your MyParams object and set that in your no-arg version. Then in Init you can check the property to determine what to do.
Something like:
ShowViewModel<MyViewModel>(new MyParams { HasNoParams = true });
public void Init(MyParams myParams)
{
if (myParams.HasNoParams)
{
// do null flow here
}
else
{
// do non-null flow here
}
}
You can use Dictionary< TKey, TValue> as your params.

java prevent a lot of if and replace it with design pattern(s)

I use this code in my application and I find it very ugly.
Is there a smart way of doing this?
for (final ApplicationCategories applicationCategorie : applicationCategories) {
if (applicationCategorie == ApplicationCategories.PROJECTS) {
// invoke right method
} else if (applicationCategorie == ApplicationCategories.CALENDAR) {
// ...
} else if (applicationCategorie == ApplicationCategories.COMMUNICATION) {
} else if (applicationCategorie == ApplicationCategories.CONTACTS) {
} else if (applicationCategorie == ApplicationCategories.DOCUMENTS) {
} else if (applicationCategorie == ApplicationCategories.WORKINGBOOK) {
}
}
My aim is to handle all application categorie enums which contained into the enum list.
The least you can do is to declare the method that handles the behaviour dependent to the enum inside ApplicationCategories. In this way, if you will add a new value to the enum, you will only to change the code relative to enum.
In this way, your code adheres to the Open Closed Principle, and so it is easier to maintain.
enum ApplicationCategories {
PROJECTS,
CALENDAR,
// And so on...
WORKINGBOOK;
public static void handle(ApplicationCategories category) {
switch (category) {
case PROJECTS:
// Code to handle projects
break;
case CALENDAR:
// Code to handle calendar
break;
// And so on
}
}
}
This solution is only feasable if you do not need any external information to handle the enum value.
Remember you can also add fields to enum values.
EDIT
You can also implement a Strategy design pattern if you need. First of all, define a strategy interface and some concrete implementations.
interface CategoryStrategy {
void handle(/* Some useful input*/);
}
class ProjectStrategy implements Strategy {
public void handle(/* Some useful input*/) {
// Do something related to projects...
}
}
class CalendarStrategy implements Strategy {
public void handle(/* Some useful input*/) {
// Do something related to calendars...
}
}
//...
Then, you can modify your enum in order to use the above strategy.
enum ApplicationCategories {
PROJECTS(new ProjectStrategy()),
CALENDAR(new CalendarStrategy()),
// And so on...
WORKINGBOOK(new WorkingBookStrategy());
private CategoryStrategy strategy;
ApplicationCategories(CategoryStrategy strategy) {
this.strategy = strategy;
}
public static void handle(ApplicationCategories category) {
category.strategy.handle(/* Some inputs */);
}
}
Clearly, the above code is only a sketch.
The design pattern you need is the Strategy.
Enums and violation of the Open/Closed Principle
The use of enums when you have to perform a different action for each defined value is a bad practice. As the software evolves, it is likely that you have to spread the if chain around different places. If you add a new enum value, you'll have to add a new if for that value in all these places. Since you may not even be able to find all the places where you have to include the new if, that is a source for bugs.
Such approach also violates the Open/Closed Principle (OCP). Just creating a method to handle each enum value doesn't make your code conformant to OCP. It will make the code more organised but doesn't change anything about the "if" issue.
Java 7 solution with Strategy Pattern
Using Java 7 or prior, you can define a ApplicationCategory interface that all categories will implement. This interface will provide a common method that each category will implement to perform the required actions for that category:
public interface ApplicationCategory {
boolean handle();
}
Usually your method should return something. Since I don't know what is your exact goal, I'm making the method to return just a boolean. It would indicate if the category was handled or not, just as an example.
Then you have to define a class implementing such an interface for each category you have. For instance:
public class CalendarCategory implements ApplicationCategory {
boolean handle(){
//the code to handle the Calendar category
return true;
}
}
public class CommunicationCategory implements ApplicationCategory {
boolean handle(){
//the code to handle the Communication category
return true;
}
}
Now you don't need the enum class and the handle method that was inside it needs to be moved elsewhere, that completely depends on your project. That handle method will be changed to:
public static void handle(ApplicationCategory category) {
//Insert here any code that may be executed,
//regardless of what category it is.
category.handle();
}
You don't need an enum anymore because any variable declared as ApplicationCategory just accepts an object that implements such an interface. If you use the enum together with the Strategy implementation, it will be yet required to change the enum class any time you add a new ApplicationCategory implementation, violating the OCP again.
If you use the Strategy pattern, you don't even need the enum anymore in this case.
Java 8 solution with functional programming and Strategy Pattern
You can more easily implement the Strategy pattern using functional programming and lambda expressions, and avoid the proliferation of class just to provide different implementations of a single method (the handle method in this case).
Since the handle method is not receiving any parameter and is retuning something, this description conforms to the Supplier functional interface. An excellent way to identify what kind of functional interface a method you are defining conforms to, it is studying the java.util.function package.
Once the type of functional interface is identified, we can create just a ApplicationCategory class (that in the Java 7 example was an interface) in a functional way, defining the previous handle method as an attribute of the Supplier type. You must define a setter for this handle attribute to enable changing the handle implementation. Defining a method as an attribute, you are enabling such a method implementation to be changed in runtime, providing a different but far simpler, easier and more maintainable implementation of the Strategy pattern.
If you need to use the category name somewhere, for instance to display it in a user interface, you could define an enum inside the ApplicationCategory class. However, there is no direct relation between the enum value and the handle provided. The enum works just as a tag for the category. It is like a "name" attribute in a Person class, that we usually just use to "tag" and print a person.
public class ApplicationCategory {
//insert all categories here
enum Type {CALENDAR, COMMUNNICATION}
/**
* The Supplier object that will handle this category object.
* It will supply (return) a boolean to indicate if the category
* was processed or not.
*/
private Supplier<Boolean> handler;
private Type type;
/**
* A constructor that will receive a Supplier defining how to
* handle the category that is being created.
*/
public ApplicationCategory(Type type, Supplier<Boolean> handler){
Objects.requireNonNull(type);
this.handler = handler;
setType(type);
}
/**
* Handle the category by calling the {#link Supplier#get()} method,
* that in turn returns a boolean.
*/
public boolean handle(){
return supplier.get();
}
public Type getType(){ return type; }
public final void setHandler(Supplier<Boolean> handler){
Objects.requiredNonNull(handler);
this.handler = handler;
}
}
If you give the behaviour that will handle the enum value at the enum constructor call, as suggested by the other answer provided here, then you don't have how to change the behaviour in runtime and it in fact doesn't conform to the Strategy pattern. Unless you really don't need that, you might implement in that way, but remember it violates the OCP.
How to use the Java 8 functional ApplicationCategory class
To instantiate a ApplicationCategory you have to provide the Type (an enum value) and the handler (that is a Supplier and can be given as a lambda expression). See the example below:
import static ApplicationCategory.CALENDAR;
public class Test {
public static void main(String args[]){
new Test();
}
public Test(){
ApplicationCategory cat = new ApplicationCategory(CALENDAR, this::calendarHandler);
System.out.println("Was " + cat + " handled? " + cat.handle());
}
private boolean calendarHandler(){
//the code required to handle the CALENDAR goes here
return true;
}
}
The this::calendarHandler instruction is a method reference to pass a "pointer" to the calendarHandler method. It is not calling the method (you can see that due to the use of :: instead of . and the lack of parenthesis), it is just defining what method has to be in fact called when the handle() method is called, as can be seen in System.out.println("Was " + cat + " handled? " + cat.handle());
By using this approach, it is possible to define different handlers for different instances of the same category or to use the same handler for a subset of categories.
Unlike other languages, Java provides facilities that specifically allow this sort of thing to be done in a safe object-oriented way.
Declare an abstract method on the enum, and then specific implementations for each enum constant. The compiler will then ensure that every constant has an implementation and nobody has to worry about missing a case somewhere as new values are added:
enum ApplicationCategories {
PROJECTS {
void handle() {
...
}
},
...
public abstract void handle();
}
Then, instead of calling some static handle(category), you just call category.handle()

Automapper - How to map with dependency on current Session object

I am using Automapper within an ASP.Net MVC application to map DTO's to ViewModel objects.
in one of my mappings I need access to an object stored in the Session object.
public override void OnAuthorization(AuthorizationContext filterContext)
{
...
SecurityToken token = SecurityTokenFactory.CreateSecurityToken(userNode);
filterContext.HttpContext.Session[securityToken] = token;
...
}
In the constructor of my controller I set up the Automapper mapping.
Mapper.CreateMap<UserReportDTO, UserDefinedReportModel>()
.ForMember(dest => dest.IsEditable, opt=>opt.ResolveUsing(src => this.IsEditable(src)));
private bool IsEditable(UserReportDTO report)
{
if (this.GetCurrentUserToken().UserVisibilityLevel == VisibilityLevel.Root)
{
return true;
}
return false;
}
public JsonResult GetVisibleUserReports()
{
...
int ID = this.GetCurrentUserToken().UserId; //This works!
var reports = Mapper.Map < UserReportDTO[], UserDefinedReportModel[] >(inputarray); //This doesn't work
...
}
What happens is that the context.Session is null.
I'm guessing this is something to do with the way Automapper resolves the mapping - maybe a reference to one Context is set when the mapping is created, and then this Context no longer exists at mapping time?
How can I resolve the issue - is there a way to pass a parameter to a mapping operation?
My temporary workaround is to map all the other fields, and then manually loop through the mapped-collection, setting the field that requires the current context, but I'm loathe to keep this approach.
A couple thoughts that might put you on the right track:
Does it make any difference if you replace ResolveUsing with MapFrom? Both seem to accept a Func<TSource, TMember>, but perhaps there are subtle differences.
Would it be possible to turn your IsEditable method into an IValueResolver then pass the required session data into the constructor using AutoMapper's ConstructedBy() feature? Here's the relevant documentation. Scroll to the "Custom constructor methods" section.

Moq testing LINQ Where queries

I'm using EF 4.1 to build a domain model. I have a Task class with a Validate(string userCode) method and in it I want to ensure the user code maps to a valid user in the database, so:
public static bool Validate(string userCode)
{
IDbSet<User> users = db.Set<User>();
var results = from u in users
where u.UserCode.Equals(userCode)
select u;
return results.FirstOrDefault() != null;
}
I can use Moq to mock IDbSet no problem. But ran into trouble with the Where call:
User user = new User { UserCode = "abc" };
IList<User> list = new List<User> { user };
var users = new Mock<IDbSet<User>>();
users.Setup(x => x.Where(It.IsAny<Expression<Func<User, bool>>>())).Returns(list.AsQueryable);
Initialization method JLTi.iRIS3.Tests.TaskTest.SetUp threw exception.
System.NotSupportedException: System.NotSupportedException: Expression
references a method that does not belong to the mocked object:
x => x.Where<User>(It.IsAny<Expression`1>()).
Other than creating a level of indirection (eg, using a ServiceLocator to get an object that runs the LINQ and then mock that method) I can't think of how else to test this, but I want to make sure there is no way before I introduce another layer. And I can see this kind of LINQ queries will be needed quite often so the service objects can quickly spiral out of control.
Could some kind soul help? Thanks!
There is an article on MSDN highlighting how to mock using moq:
The gist of it is to represent linq to entities operations with linq to objects.
var mockSet = new Mock<DbSet<Blog>>();
mockSet.As<IQueryable<Blog>>().Setup(m => m.Provider).Returns(data.Provider);
mockSet.As<IQueryable<Blog>>().Setup(m => m.Expression).Returns(data.Expression);
mockSet.As<IQueryable<Blog>>().Setup(m => m.ElementType).Returns(data.ElementType);
mockSet.As<IQueryable<Blog>>().Setup(m => m.GetEnumerator()).Returns(data.GetEnumerator());
As Ladislav points out there are disadvantages to this as Linq To Objects is simply different to Linq to Entities so it may result in false positives. But it now being an MSDN article it does point that it is at least possible and perhaps recommended in some cases?
One thing that may of changed since the original answers to this post is that the Entity Framework team have opened up areas of Entity Framework in EF 6.0 to make it easier to mock it's inners.
Although I have not tried this, because IDBSet implements IEnumerable you might have to mock the enumerator method so the linq statements will pick up your list of users. You don't actually want to mock linq but by the looks of your code you want to test whether you are finding the right user based on the UserCode which I think is a valid unit test.
var user = new User { UserCode = "abc" };
var list = new List<User> { user };
var users = new Mock<IDbSet<User>>();
users.Setup(x => x.GetEnumerator()).Returns(list.GetEnumerator());
You might get a conflict with the non-generic version of the GetEnumerator but it this might help you on the right track.
Then you have to then place the mocked object on the data context which depends on other code that we don't see.
As I know Moq is able to set up only virtual methods of mocked object itself but you are trying to set up extensions (static) method - no way! These methods are absolutely outside of your mock scope.
Moreover that code is hard to test and requires too much initialization to be able to test it. Use this instead:
internal virtual IQueryable<User> GetUserSet()
{
return db.Set<User>();
}
public bool Validate(string userCode)
{
IQueryable<User> users = GetUserSet();
var results = from u in users
where u.UserCode.Equals(userCode)
select u;
return results.FirstOrDefault() != null;
}
You will just need to set up GetUserSet to return your list. Such testing has some major issues:
You are not testing the real implementation - in case of EF mocking sets is stupid approach because once you do it you change linq-to-entities to linq-to-objects. Those two are totally different and linq-to-entities is only small subset of linq-to-objects = your unit tests can pass with linq-to-objects but your code will fail at runtime.
Once you use this approach you cannot use Include because include is dependent on DbQuery / DbSet. Again you need integration test to use it.
This doesn't test that your lazy loading works
The better approach is removing your linq queries from Validate method - just call them as another virtual method of the object. Unit test your Validate method with mocked query methods and use integration tests to test queries themselves.
I found it easier just to write the stub:
internal class FakeDbSet<T> : IDbSet<T>where T : class
{
readonly HashSet<T> _data;
readonly IQueryable _query;
public FakeDbSet()
{
_data = new HashSet<T>();
_query = _data.AsQueryable();
}
public virtual T Find(params object[] keyValues)
{
throw new NotImplementedException("Derive from FakeDbSet<T> and override Find");
}
public T Add(T item)
{
_data.Add(item);
return item;
}
public T Remove(T item)
{
_data.Remove(item);
return item;
}
public T Attach(T item)
{
_data.Add(item);
return item;
}
public void Detach(T item)
{
_data.Remove(item);
}
Type IQueryable.ElementType
{
get { return _query.ElementType; }
}
Expression IQueryable.Expression
{
get { return _query.Expression; }
}
IQueryProvider IQueryable.Provider
{
get { return _query.Provider; }
}
IEnumerator IEnumerable.GetEnumerator()
{
return _data.GetEnumerator();
}
IEnumerator<T> IEnumerable<T>.GetEnumerator()
{
return _data.GetEnumerator();
}
public TDerivedEntity Create<TDerivedEntity>() where TDerivedEntity : class, T
{
return Activator.CreateInstance<TDerivedEntity>();
}
public T Create()
{
return Activator.CreateInstance<T>();
}
public ObservableCollection<T> Local
{
get
{
return new ObservableCollection<T>(_data);
}
}

Problems writing C# method parameter validation that supports fluent interface (call chaining)

I'm trying to write a generic method parameter validation functionality that can be chained (fluent interface) to attach more and more validations/checks like:
public void SomeMethod(User user, string description)
{
ParameterHelper
.Create(() => user)
.RejectNull();
ParameterHelper
.Create(() => description)
.RejectNull()
.RejectEmptyString();
// now this would be luxurious
ParameterHelper
.Create(() => new { user = user, desc = description })
.RejectNull(o => o.user)
.RejectNull(o => o.desc)
.RejectEmptyString(o => o.desc);
}
I would like to use this helper class to test method parameters for certain values before using them (most of the time null will be tested).
Current state of affairs
I first started writing static helper class without the Create() method like:
public static class ParameterHelper
{
public static void RejectNull(Expression<Func<T>> expr)
{
if (expr.Compile()().Equals(default(T)))
{
MemberExpression param = (MemberExpression)expr.Body;
throw new ArgumentNullException(param.Member.Name);
}
}
}
But this doesn't allow chaining. That's why I created the Create() method that would return something that can be used by chained extension methods.
The problem
I would like to avoid multiple Compile() calls, so basically my Create() method should return Func<T> and reject methods should be extension methods of Func<T>.
If my Create() does return Func<T> I don't get the chance to read parameter names that should be supplied to various exceptions (using MemberExpression).
If I return Expression<Func<T>> instead I will have to call Compile() in each Reject extension method.
Questions
Is there a C# library that already does this kind of chaining?
If not, what do you suggest how this should be done? Any examples from the web would be warmly welcome.
Additional note
I should point out that complex/long validation invocation code is not an option here, because my current validation is done like:
if (user == null)
{
throw new ArgumentNullException("user");
}
or
if (string.IsNullOrEmpty(description))
{
throw new ArgumentNullException("description");
}
Which has two major drawbacks:
I repeat the same lines of code over and over
it uses magic strings
So validation should be done with a one liner per check as described above in the desired scenario.
There is a simple way to implement such a fluent interface. Your 'ParameterHelper.Create' method should return an instance of some class (this class is named Requirements below). This instance should hold the expression which was passed to Create. Also this class should have Require... instance methods which will validate expression and return this. Requirements class can be a private class inside ParameterHelper. I would also introduce an interface for this requirements chain (this interface is named IRequirements below. Sample:
public static class ParameterHelper
{
public static IRequirements Create<T>(Expression<Func<T>> expression)
{
return new Requirements{ Expression = expression };
}
private class Requirements<T> : IRequirements
{
public readonly Expression<Func<T>> Expression { get; set; }
public IRequirements RejectNull()
{
if (Expression .Compile()().Equals(default(T)))
{
MemberExpression param = (MemberExpression)Expression.Body;
throw new ArgumentNullException(param.Member.Name);
}
return this;
}
// other Require... methods implemented in the same way
}
}
public interface IRequirements
{
IRequirements RejectNull();
}
This approach will allow you implementing your luxurious solution - you just need to add a corresponding parameters to Reject... methods. Also you will probably need to make IRequirements interface generic.
Robert,
I have a library that solves this problem. It is called Bytes2you.Validation (Project). It is fast, extensible, intuitive and easy-to-use C# library providing fluent APIs for argument validation.
It focuses exactly on the problem that you want to solve, but does not use expressions. This is so, because they are a lot slower than just passing the argument name. For a library like that, that is designed to be used everywhere the performance is one of the most critical features.
For example:
Guard.WhenArgument(stringArgument,"stringArgument").IsNullOrEmpty().IsEqual("xxx").Throw();
// Which means - when stringArgument is null or empty OR is equal to "xxx" we will throw exception. If it is null, we will throw ArgumentNullException. If it is equal to "xxx", we will throw ArgumentException.

Resources