Moq and calling back to set a class' values - linq

I have a mocked DTO class that has properties in it I'm setting via a callback function. This works below for me, but is there a cleaner way to go about it?
Mock<MyDto> _MyDto = new Mock<MyDto>();
_MyDto.Setup(dto => dto).Callback<MyDto>(dto =>
{
dto.FirstName = "John";
dto.LastName = "Doe";
});
I'd like to set those properties in the Setup call if possible, but it accepts an expression and I can't do a multi-line statement in there. But my Linq knowledge isn't encyclopedic and I was wondering if there was a better to approach what I'm doing.

According to the Moq quickstart guide to properties, you could possibly change your code to look like this instead:
_MyDto.SetupProperty(dto => dto.FirstName, "John");
_MyDto.SetupProperty(dto => dto.LastName, "Doe");
I've not yet had the chance to use Moq myself, but this appears to be the way to mock properties in Moq.

I think you misunderstand what the Setup() method is for. You're not supposed to call it just once with all of the initialization code. Instead, you call it once for each individual item that you want to setup.

Related

Are there penalties for just using the new keyword instead of creating a class variable before calling the class method?

Example
(1)
var classVar = new class();
classVar.Method();
(2)
new class().Method();
I like the second way, less wordy.
Is there a performance difference?
Is it considered bad coding practice?
If your Method() doesn't use anything from that class, why is it defined there? You could use namespace instead.
The only difference between your (1) and (2) is that the class instance is destructed immediately in (2).
in your case Method seems to be static (ie there is no useful data stored inside the instance of 'class' (note I am ignoring all the invalid / not recommended name issues). Assuming this is c# but all languages have the same ideas, you would go
public class class{ // ugh
public void static Method(){
Console.WriteLine("I am Method");
}
}
now you can go
class.Method();
so the code is neatly filed away inside 'class' but you dont have to pay any overhead.
If you really need to instantiate 'class' then presumably you need to do more than just call one method on it. In which case
new class().Method();
makes no sense, since you call create it, call a method and destroy it.
Really a more concrete example is needed

what's the best way to use "isSomething"?

Hey guys,
I'm not having a problem, I was just wondering what's the best way of implementing isSomthing in OOP paradigm?
Take this example: we want to know if the user was temporarily (like 10 minutes) banned. Here are the two options:
Implementing isTempBanned() method in the User class. Then whenever we want to check if user is banned, we just call this method. no change to the other parts of the code is required.
Adding a isTempBanned property to the User class. Then whenever the state of user's ban changes, we update this property accordingly. Then when we need to know, we just use this property.
Can you explain Pros and Cons of each way? from these standpoints:
performance
code maintainability
clean code
readability
etc...
Keep in mind that there is no better way. I'm just asking to know when should I use the first method and when to use the second one.
Ultimately you have to use both of them!
based on Encapsulation principle , think of your example as a getter/setter scenario, to keep bugs as low as possible,
getter is User.isBanned method, setter is User.banUser method.
class User{
banned_until : Date = null
isBanned(){
if(this.banned_until){
return this.banned_until.valueOf() > new Date().valueOf();
}
return false;
}
banUser(){
this.banned_until = new Date() ///any date in future ....
}
}
isSomthing is usually used for boolean. no matter what data type you use. all differences are method and property differences.
I suggest you read this:
Properties vs Methods

best practice to get the default object wrapper?

when creating custom method, I implements TemplateMethodModelEx and returns SimpleSequence object.
according to the API, I should use this constructor:
SimpleSequence(ObjectWrapper wrapper)
since I am setting incompatibleImprovements as 2.3.24, the doc said I can simply use Configuration instance's getObjectWrapper(). My problem is when implementing TemplateMethodModelEx, I have no access to the current config unless I pass cfg to the method's constuctor. then the root.put would look like:
root.put("getMeList", new GetMeListMethod(cfg));
this looks odd to me, i wonder whats the right to construct this kind of SimpleSquence model and whats the right way to get the default object wrapper.
Thanks a lot
You should pass in the ObjectWrapper as the constructor parameter. (It's unrelated to incompatibleImprovements 2.3.24.) Any TemplateModel that creates other TemplateModel-s (like TemplteSequenceModel-s, TemplateHashModel-s, TemplateMethodModel-s) used to work like that. This is normally not apparent because they are created by an ObjectWrapper. If you do the TemplateModel-s manually however (which is fine), then you will face this fact.

How can I modify the fixture my custom theory data attribute creates for AutoFixture?

I'm really appreciating the power of AutoFixture coupled with XUnit's theories. I've recently adopted the use of encapsulating customizations and providing them to my tests via an attribute.
On certain occasions, I need a one-off scenario to run my test with. When I use an AutoDomainDataAttribute, like above, can I ask for an IFixture and expect to get the same instance created by the attribute?
In my scenario, I'm using MultipleCustomization by default for collections, etc. However, in this one case, I want only a single item sent to my SUT's constructor. So, I've defined my test method like so:
[Theory, AutoDomainData]
public void SomeTest(IFixture fixture) {
fixture.RepeatCount = 1;
var sut = fixture.CreateAnonymous<Product>();
...
}
Unfortunately, I'm getting an exception when creating the anonymous Product. Other tests work just fine, if I ask for a Product as a method parameter with those attributes. It's only an issue in this particular case, where I'm hoping that the fixture parameter is the same one created by my AutoDomainDataAttribute.
Product's constructor expects an IEnumerable that normally gets populate with 3 items, due to the customizations I have in-place via AutoDomainData. Currently, my DomainCustomization is a CompositeCustomization made up of MultipleCustomization and AutMoqCustomization, in that order.
The exception is: "InvalidCastException: Unable to cast object of type 'Castle.Proxies.ObjectProxy' to type 'Product'."
If you need the same Fixture instance as the one active in the attribute, you can inject the Fixture into itself in a Customization, like this:
public class InjectFixtureIntoItself : ICustomization
{
public void Customize(IFixture fixture)
{
fixture.Inject(fixture);
}
}
Just remember to add this to your CompositeCustomization before AutoMoqCustomization, since IFixture is an interface, and if AutoMoqCustomization comes first, you'll get a Mock instance instead - AFAICT, that's what's currently happening with the dynamic Castle proxy.
However, if you really need a Fixture instance, why not just write a regular, imperative test method:
[Fact]
public void SomeTest()
{
var fixture = new Fixture().Customize(new DomainCustomization());
fixture.RepeatCount = 1;
var sut = fixture.CreateAnonymous<Product>();
// ...
}
That seems to me to be much easier... I occasionally do this myself too...
Still, I wonder if you couldn't phrase your API or test case in a different way to make the whole issue go away. I very rarely find that I have to manipulate the RepeatCount property these days, so I wonder why you would want to do that?
That's probably the subject of a separate Stack Overflow question, though...

Specify ASP.NET MVC 3 Routes symbolically

I really like the ASP.NET MVC 3 framework. Or at least, it sure is incomparably better than trying to fool with ASP.NET 3.5 or 4.0. However, I am just really confused about something. Why did they choose to specify routes with strings?
IOW, I am told to specify my routes like this (for instance):
... new { controller = "Products", action = "List", id = UrlParameter.Optional }
This route matches a ProductsController.List() method. Let's say I'm in a refactoring mood and I want to rename my ProductsController to InventoryController. After using my renaming tool of choice, I have open up Global.aspx and go through all my routes and change all these stupid strings to "Inventory". You might respond that I can do a find and replace... but come on! I feel like that is such a last-generation answer.
I love refactoring my code as I come to understand my domain better. I don't want to use stupid (I say stupid because they have no significance to the compiler) strings to refer to symbolic/semantic code constructs that correspond exactly to type and method names that are ultimately stored in a symbol table. What is the point? Why bother with types at all? Let's just go back to writing scripts using associative arrays and dictionaries to represent our domain model... it seems to me that the benefit of strong typing is greatly lessened when we mix it with string references.
Seriously, though, an option would be reflection. Would there be a performance hit for this? I suppose the MVC framework must be using reflection on that "Products" string to get my ProductsController, so... But also, you would have to remove the "Controller" portion of the type name, as follows:
= typeof(ProductsController).Name.Replace("Controller", string.Empty)
I could use the following helper function to make it a little DRYer:
public string GetControllerName(Type controller)
{
return controller.Name.Replace("Controller", string.Empty);
}
Benchmarking is in order, if this is the only way to avoid those strings... Still, this is stupid. I'm using reflection on a type to get a string that MVC is going to use in conjunction with reflection to get the type I originally had in the first place.
Is there some reason not take the next (logical?) step and have the controller and action properties expect Types and Delegates directly? Wouldn't this simply be cleaner and clearer? So far as I understand, a fundamental aspect of MVC is convention over configuration, but routing with those strings just seems to be a furtive form of configuration to me.
Is there another way around this? I am still new to MVC. I've read that we can replace these routing components. Does anyone know if it is possible to do what I'm talking about? And if it's not possible, well... am I alone here? Am I missing something? Some overriding reason why it is essential that these routes be set by dumb strings? If not, could this maybe be something to lobby for?
Am I alone in hating it when strings are used in this way? I still think C# needs something akin to Ruby's symbols and Lisp's keywords that our refactoring tools could take advantage of. Sort of like "string enumerations" where the enumeration value name is at the same time the value.
I understand that parts of this question are subjective, but I am also looking for the objective answer on whether it is possible to directly use types and delegates to specify these routing configurations.
Thank you,
Jeromeyers
Personally I never had problems with the way routes are defined because I always unit test them. So if I am in a refactoring mood, my unit tests always guarantee me that the routes will behave as I want.
Of course if you are still not satisfied with the way the ASP.NET MVC team designed the framework (don't hesitate to open a ticket and vote for improvement in future versions) you could always write a custom route:
public class IHateMagicStringsRoute<T> : Route where T : Controller
{
public IHateMagicStringsRoute(
string url,
Expression<Func<T, ActionResult>> expression
) : base(url, Parse(expression), new MvcRouteHandler())
{ }
private static RouteValueDictionary Parse(Expression<Func<T, ActionResult>> expression)
{
var mce = expression.Body as MethodCallExpression;
if (mce != null)
{
return new RouteValueDictionary(new
{
controller = typeof(T).Name.Replace("Controller", ""),
action = mce.Method.Name
});
}
return null;
}
}
and then instead of:
routes.MapRoute(
"Default",
"{controller}/{action}",
new { controller = "Home", action = "Index" }
);
you could:
routes.Add(
new IHateMagicStringsRoute<HomeController>(
"{controller}/{action}",
x => x.Index()
)
);
Now you can rename your controllers and actions as much as you like.

Resources