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.
Related
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
I have a piece of code like the following:
public class ActivityHelper
{
public void SetDate(IList<Activity> anActivityList)
{
foreach(Activity current in anActivityList)
{
current.Date = DateTime.Now;
}
}
//More methods, properties, fields, etc...
}
This could easily be converted to an extension method. For example:
public static void SetDate(this IList<Activity> aList)
{
foreach(Activity current in anActivityList)
{
current.Date = DateTime.Now;
}
}
The original function doesn't use any instance specific data or methods from the ActivityHelper class which makes it seem like it is in the incorrect place. Is this the correct time to write an extension method? What are the correct scenarios in which to create extension methods?
Brad Adams has written about extension method design guidelines:
CONSIDER using extension methods in any of the following scenarios:
To provide helper functionality relevant to every implementation of an interface, if said functionality can be written in terms of the core interface. This is because concrete implementations cannot otherwise be assigned to interfaces. For example, the LINQ to Objects operators are implemented as extension methods for all IEnumerable types. Thus, any IEnumerable<> implementation is automatically LINQ-enabled.
When an instance method would introduce a dependency on some type, but such a dependency would break dependency management rules. For example, a dependency from String to System.Uri is probably not desirable, and so String.ToUri() instance method returning System.Uri would be the wrong design from a dependency management perspective. A static extension method Uri.ToUri(this string str) returning System.Uri would be a much better design.
I think Extension methods are only appropriate if there is a compelling reason to make the method an extension method.
If the type is one you do not control, and the method should appear to be integral to the type, or if there is a compelling reason to not put the method directly on the type (such as creating an unwanted dependency) then an extension method could be appropriate.
Personally, if the expectation of the user of your API will already be to use the "ActivityHelper" class when working with collections of Activities, then I would probably not create an extension method for this. A standard, non-extension method will actually be a simpler API, since it's easily understood and discoverable. Extension methods are tricky from a usage standpoint - you're calling a method that "looks like" it exists somewhere other than where it actually exists. While this can simplify syntax, it reduces maintainability and discoverability.
In my experience extension methods work best when they:
Don't have side-effects (most of the extension methods my team wrote that have side-effects, we ended up removing because they caused more problems than they helped)
Offer functionality that applies to every possible instance or value of the type they're extending. (Again citing an example from my team, string.NormalizeUrl() is not appropriate because not all strings are even URLs anyway)
Well i usually create extension methods to help me write codes which have a smooth flow. Its generally depends upon the method you are creating.
If you feel that the method should have already been in framework and is too general then its okay to create an extension method for that.
But you need to first analyze that the class you are extending will always will be in state that your extension method can handle.
For Guidelines here to Brad's Article
http://blogs.msdn.com/b/brada/archive/2009/01/12/framework-design-guidelines-extension-methods.aspx
In essence, Extension Methods provide a more fluent style syntax for Helper methods. This translates into the ability to seemingly add functionality to types or all implementations of interfaces.
However, I generally steer away from declaring Extension Methods with a void returntype, as I feel the usefulness of this fluent style syntax, which allows you to compose statements, is negated when the method in question doesn't return anything.
However, I guess it can be handy to have your methods picked up by IntelliSense... :-)
I have two interfaces IDto1 and IDto2. IDto2 inherits IDto1. Both interfaces are for DTOs and so I wish to keep "complex" code out of their implementations - I do this by putting a single extension method Initialize in a static class for each interface.
So I end up with the following types IDto1, IDto2, IDto1Extensions, IDto2Extensions.
I wish to have the Initialize extension method on both interfaces, but for each to have a different implementation.
In client code I want to use code like this:
(dto as IDto1).Initialize();
...and I'd like the relevant extension method to be invoked based on the resolved type of the dto variable at runtime.
Is this possible in C# and if not why not?
Edit:
Sorry, of course this:
(dto as IDto1).Initialize();
...will invoke the Initialize method on the IDto1 type. I meant that the dto variable would be passed in as an argument to a method, under which circumstances I believe the method would be chosen polymorphically given the inheritance hierarchy I specified earlier.
Thanks for all your answers.
What you are trying to achieve here is some sort of polymorphysm. Extension methods are static methods. In OOP polymorphysm is applicable only for instance methods.
An option could be to switch to abstract classes.
Looking at your statement:
(dto as IDto1).Initialize();
...and I'd like the relevant extension method to be invoked based on the resolved type of the dto variable at runtime.
The "resolved type" of the thing in brackets is precisely IDto1. It cannot be anything else, so that is what the compiler will work with. Indeed variables never change type (I assume you mean the object referred to by the variable's value).
In .NET 4.0 / C# 4.0, an option here for duck-typing might be an instance method and dynamic...
((dynamic)dto).Initialize();
...but to be honest I can't see why you can't just add your Initialize method to the interface and use polymorphism, since that sounds the closest to what you are trying to describe.
What you are trying to accomplish is not possible because extension methods are resolved at compile time, while in your case the actual type of the dto variable is known only at runtime.
If you want to make your code more dynamic you can define the class that you want in configuration file and use something like this
String className = ConfigurationManager.AppSettings["Interface"].ToString();
IDto1 dto = (IDto1)Activator.CreateInstance(Type.GetType(className));
In this sample I use the first line to get's the class name.
The second line create an instance of the Object.
Guilherme Ferreira
http://guilhermeferreira.wordpress.com/
This sounds like a job for an abstract base class.
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...
I recently asked this question:
Compiler error referencing custom C# extension method
Marc Gravell answer was perfect and it solved my problem. But it gave me something to think about...
If and Extension method must be placed on a Static Class and the method itself must be static, why can't we create a static Extension method?
I understand that the parameter marked as "this" will be used to allow access to an instance of the object we are extending. What I do not understand is why can't a method be created to be static... it just seems to me that this is a senseless limitation...
My question is: Why can't we create an extension method that will work as a static Method?
I expect the real answer is simply: there wasn't a good use-case. For instances, the advantage is that it enables a fluent-API over existing types (that don't themselves provide the logic) - i.e.
var foo = data.Where(x=>x.IsActive).OrderBy(x=>x.Price).First();
which enables LINQ:
var foo = (from x in data
where x.IsActive
order by x.Price
select x).First();
With static methods, this simply isn't an issue, so there is no justification; just use the static method on the second type.
As it is, extension methods are not properly object orientated - they are a pragmatic abuse to make life easier at the expense of purity. There was no reason to dilute static methods in the same way.
Because that feature doesn't exist in C#.
As a workaround, static methods can be implemented in another class and called through that class to provide the added functionality.
For example, XNA has a MathHelper class which ideally would have been static extensions to the Math class.
The community is asking if we think it's a good idea for C# 4.0
My thinking would be for compatibility - if you suddenly made all static methods extension methods with the need for the this operator you could inadvertently break code which now is overriding a normal method with an extension method.
The this parameter allows control and thus doesn't break compatibility.
Just an idea though.
First of all you would have to add yet another syntax to indicate you want to extend the static methods of the existing type. When extending syntax you really need a very good reason to do so.
Lets imagine I have a class called MyExts which allow me to add extension methods to MyClass. Why would:-
MyClass.DoSomethingExtra();
be better than
MyExts.DoSomethingExtra();
?