Why or how to use NUnit methods with ICollection<T> - c#

Some of NUnit's Assert methods are overloaded to use ICollection but not ICollection<T> and thus you can't use them.
Is there anyway around this? Heck, am I doing something stupid?
I'm having to drop back to using Assert.AreEqual rather than specialised methods and its making my tests ugly.
Any advice?
Edit:
Thanks for the responses. The That method of NUnit seems interesting so I'll look into it at a later date.
Mark correctly mentioned this, but NUnit Collection Asserts are excellent. I've recently used them on some new tests and found them excellent to work with.

I don't know if this is what you're looking for, but for generic collections instead of using:
Assert.Contains(member, list);
I use:
Assert.That(list.Contains(member));
which I find almost as readable.

ICollection and ICollection<T> are different contracts - one does not inherit the other.
http://msdn.microsoft.com/en-us/library/system.collections.icollection_members.aspx
http://msdn.microsoft.com/en-us/library/y2fx0ty0.aspx
If you have a generic collection you can call ToList() on it and get a List<T>, which happens to implement the non-generic ICollection as well. Then use that List in the NUnit Assert method.

There are a set of CollectionAsserts, or you could inherit your test from AssertHelper and use syntax like
Expect(actual, Is.EquivalentTo(expected));
A look at the documentation should give you the syntax for the constraints that apply to collections.
Here's a link (this is version 2.5.2)
N.B. Expect is just shorthand for Assert.That...

Related

Extending Simple.Data with assertions

I'm using this very nice mini ORM, Simple.Data, to setup a lot of test data, quick and easy.
I would really like to extend it for assertions. For example i would like to assert on count:
Db.MyTable.GetCount(); <- Returns a dynamic
So that I could evaluate more or less like you would do with FluentAssertions.
It could look like this:
Db.MyTable.GetCount().ShouldBe(X);
But I'm finding it very hard to do this without loosing the advantage of dynamics.
Does anyone have a hint of how this could be done or if its even possible within reason?
I'm currently traversing the src at GitHub trying to find a way i can do this locally and toying around with impromptu to find a way.
Sadly, there is no happy answer to this. Dynamic and extension methods do not mix, as explained by Jon S and Eric L here: Extension method and dynamic object
The answer, as in that question, is either to invoke ShouldBe as a static method:
AssertionExtensions.ShouldBe(Db.MyTable.GetCount(), 3);
or to inline-cast the method's return value to the known type:
((int)Db.MyTable.GetCount()).ShouldBe(3);
Or, as you are investigating, to use Impromptu to apply an interface to MyTable with a GetCount method. I'm guessing you've seen my blog post on Simple.Data and Impromptu, but if you haven't: http://blog.markrendle.net/2012/10/12/howto-dial-up-the-static-on-simple-data/
In the classes you are creating why dont you create your own custom assertion class and make the object classes you are creating inherit from them.
public class MyClass : MyCustomExceptionClass
{
}
In that way it would be easier for you to test the methods in the way you want

Why is it preferred to use IEnumerable<T> to List<T>

I have been hearing that it is important to use the lowest class possible when passing parameters to methods. Why is this? Also where can i find more information on what the class hierarchy is? I would like to know what IEnumerable inheriated from and so forth.
If you use IEnumerable<T> as a parameter type, then you can pass in any type that implements that interface. That includes List<T>, Stack<T>, Queue<T>, etc.
It also includes various anonymous types that might be the result of a LINQ query, and also the very important IQueryable<T>.
By using "low-level" arguments, you give your method the ability to work on a larger variety of objects. It encourages writing generic re-usable methods.
MSDN can tell you what different things inherit from (in the case of IEnumerable, it inherits from nothing, because it represents pretty much the most primitive idea of a "list")
IEnumerable is a read-only sequence, while a List can be appended to.
If you design your public API so that it exposes IList<T> all over the place and then realize that you want to return a read only list, you have to either break your code by changing to IEnumerable<T> or use the horrible ReadOnlyCollection. I call it horrible because it throws exceptions on .Add/.Remove etc.
So if you only need to read, return IEnumerable, if your callers need to add/append, return IList.
On another note: Never return a List<T>, always an IList<T>. The reason is that List is a concrete class that can't be overridden in any sensible way, while IList is an interface that allows you to change the actual implementation without breaking the public contract.
The quickest thing I can think of is this: what happens if you no longer want your implementation to be of type List<T>?
Let's say you one day decide to refactor your application to use a LinkedList<T> or a SortedList<T>, all you have to change is that type instead of all of the types in all of the methods you might be passing your collection around to.
You can improve the maintainability of your code by using this technique.
The idea is to maximize the flexibility of your function. If you require a List<T>, then callers must have one to pass in. If they don't have one handy, they'll have to create one, and this is expensive. If you require IEnumerable<T>, on the other hand, then they can pass in any collection.
The best place to fnd information on the class heiarchy in .NET is MSDN.

When should extension methods be avoided?

Before you start pointing me to duplicates just know that I have read nearly all the posts on SO about extension methods. I am just trying to play devil's advocate for a minute to consider the alternative to my working opinion.
Recently I was working on a project and a need came up for a method to be a base of an interface. So I suggested we write an extension method and it was shot down. Saying it added complexity and harder to debug.
I of course argued and got on SO to find all the wonderful posts that show the many reasons why to use extension methods. Not to forget that a lot of the .net framework uses them. We eventually did not use it as I was overruled by the team.
But then it got me thinking, are there times when an extension method could be used but shouldn't be?
I really couldn't think of any but thought I would post here and see if anyone could think of any other reasons why they shouldn't be used.
Any time you have a function which is "generally applicable" to an object of a certain type, regardless of its state, an extension method is a good choice.
For example, today I added two new extension methods to our codebase:
public static XElement ToXElement(this XmlElement element) { }
public static XmlElement ToXmlElement(this XElement element) { }
Both of these are, generally speaking, valid on the types they extend regardless of the state of the instance or where we are using it.
If your method does not meet that criteria, it should probably be moved to a helper method closer to the context where the particular case is always true or easily checked.
For example, a developer recently nominated this to be an extension method:
public static bool ParseYesNoBool(this string input) { }
There are two problems here: first, this will appear on all strings in the application, even though the number of strings which might ever be candidates for this case are very small. So we've broken the first rule, in that it is not useful regardless of state. Similarly, but second, the consumer of this functionality is limited to a single parser for one particular connector to an external system. So promoting implementation-specific functionality into the general-use namespace makes no sense. This was downgraded to a helper method in the parser.
As far as readability and debugging, that is just incorrect for a developer of any reasonable skill level.
In general if you control the source-code for the assembly and adding the method does not cause any breaking changes to existing code (which would have been the case if for example LINQ had not been implemented via extension methods) it is better to just add a normal method.
This discussion of the Framework Design Guildelines section on extension methods contains some good advice. I think the relevant portion for your scenario is:
To provide helper functionality relevant to every implementation of an interface, if said functionality can be written in terms of the core interface.
If your proposed usage did not pass that test then it should have been shot down.
I would say you should avoid them when "they do not make the intend of the code more clear". Of course, whether or not some code (or codeing style) is "more clear" varying widely between people, so that's pretty much useless. (I had one boss who said we shoudl avoid using interfaces because they made the code "too complex and hard to understand")
Extension methods enable you to "add" methods to existing types without creating a new derived type, recompiling, or otherwise modifying the original type.
Any time you break the intent and design for the feature I would recommend reconsidering the use of an extension method. I see a few situations when you don't want to use an Extension method:
1) Changing the Object Model to allow for an Extension method: The class you want to create an extension on is an abstract class. This is going to require you either make each inherited class it's own version of the extension or remove abstract from the class. Either way, you are changing the object model in order to use an extension method.
2) Forgetting the Decorator Pattern: The number of extension methods you create for a class exceeds three. I find it is easier to organize/communicate and maintain the domain/object model with decorated objects than with extended objects. However, the opposite is also true: If a decorated object has less than four methods, I find a lot of almost "empty" objects in my project.
3) Private functions: Private functions are meant to modify(create, delete, etc..) the object and extension methods are meant to use the type, much like a struct would. If you find the extension is being assigned to another instance of the type then it probably should not be in an extension.

Mocking the is operator in Moq

Is there a way to get my mocks to impersonate a type? I am trying to do something like this:
var myMock = new Mock<IMyType>();
myMock.Setup(x => x.GetType()).Returns(typeof(MyTypeImpl));
however, GetType is not overrideable.
Any suggestions?
I know this is an old post, but I was searching for a solution to this issue...
Using Moq it is possible to add the standard GetType signature to your interface, allowing Moq to mock the method, without the need for writing any more code as the method is already implemented for you.
Type GetType();
Instead of using the is operator to check types, you could (not should) implement your own overridable interface method that performs a similar function, and implement it with the is operator (or typeof()/GetType()) on your usual bunch of classes.
That said, if you're using the is operator in a way that needs to be testable like this, it's more likely than not that you're basically defeating the purpose of polymorphism and interfaces somewhere along the line. I'd think about whether I could just get rid of it.

About System.Linq.Lookup class

I came across this class while reading a C# book and have some questions.
Why is this added into System.Linq namespace and not into usuall Collections namespace?
What the intention behind this class is
Why this class is not intended for direct instantiation? This is available through the ToLookup extension only, right?
Purpose of the class: a dictionary where a key can map to multiple values. Think of it as being for grouping rather than one-to-one mapping.
Only through ToLookup decision: Pass. Again, seems like a bad call to me. On the other hand, it means that the result is immutable to the outside world, which is quite nice. It's quite easy to write your own collection which supports this, of course - but it would be have been quite nice to have it in the collections "properly". My guess is that MS didn't have the time/money to go through the pretty rigorous design/test required to make it a first class collections decision.
Namespace decision: Probably related to the above. Having a version in System.Collections.Generic which you couldn't create yourself would have been a bit odd.
As an aside, note that MiscUtil also includes a MiscUtil.Linq.EditableLookup<,> class, that is similar; it implements the regular ILookup<,> interface, but is fully mutable - so you can create it and add your own values.

Categories

Resources