Populating a Collection Property of a fixture with autofixture - autofixture

I have just started using AutoFixture, and i am getting the basics down (from what i can see there is much more to it) but i am having an issue and i am not 100% sure what the best practice is for stuff like this.
I am testing a controller, and part of the process is the action can return one of two views.
If a category has children - show the category listing view
If a category does not have children show the product listing view
So i am thinking of a few tests for that behavior, but the fixture data returned would be different. One would return a count of 0, the other a greater count then zero, so i would like the fixture to help me with that.
I have been looking around, and maybe i have to create a customisation of some sort, but was hoping the basic API could help me here. I tried this:
var category = _fixture.Build<Category>()
.Do(x => x.SubCategories = _fixture.CreateMany<Category>(3).ToList())
.Create();
_fakeCategoryService
.Setup(x => x.GetById(id))
.Returns(category);
This compiles and tests run (and fail), but the sub categories always has a count of 0, so i am thinking my call to Create Many in the do is all wrong (it kinda looks wrong but i am still unsure what it should be replaced with).
UPDATE: should read the cheat sheet a bit better!
var category = _fixture.Build<Category>()
.With(x => x.SubCategories, _fixture.CreateMany<Category>(3).ToList())
.Create();
This works, if there is a better way please let me know.

Yes, Build is correct.
If you want to customize the creation algorithm for a single Category use Build:
var actual = fixture
.Build<Category>()
.With(x => x.SubCategories,
fixture.CreateMany<Category>().ToList())
.Create();
Assert.NotEmpty(actual.SubCategories);
If you want to customize the creation algorithm for all Category instances use Customize:
fixture.Customize<Category>(c => c
.With(x => x.SubCategories,
fixture.CreateMany<Category>().ToList()));
var actual = fixture.Create<Category>();
Assert.NotEmpty(actual.SubCategories);

was hoping the basic API could help me here
It does help you, if you know how to listen :) AutoFixture was originally build as a tool for Test-Driven Development (TDD), and TDD is all about feedback. In the spirit of GOOS, you should listen to your tests. In this case it's saying the same as the Framework Design Guidelines:
DO NOT provide settable collection properties.
Instead of assigning a list wholesale to a property, consider
making the collection property read-only, and let clients invoke Add, etc.
taking the collection as a constructor parameter instead of mutating property
In the latter case, AutoFixture will automatically provide a populated collection when it invokes the constructor, although in this particular case, since you have a potentially recursive graph, you may need to explicitly handle it.
In the first case, AutoFixture doesn't do anything out of the box, but has an AddManyTo extension method, enabling you to fill a collection in a single statement:
fixture.AddManyTo(category.SubCategories);

You can do this stub with a custom list:
var stub = _fixture.Build<Entity>().With(x=> x.field, config).CreateMany().ToList();
Documentation.

Related

How can I get the rootNodeID of react element

I need to capture event depend on whether the event target is a special view.
Something like view._rootNodeID === 'event.dispatchMarker'.
But there seems to be no way to get _rootNodeID because the only reference I can get is not the actual ReactNativeBaseComponent but rather something like baking data instance used to construct ReactNativeBaseComponent . And ReactNativeBaseComponent is the one really owns _rootNodeID, if I understand source code correctly.
I can alter react-native source code to achieve what I want but I want to make sure there is no better way.
ReactInstanceMap exists for this.
const ReactInstanceMap = require('ReactInstanceMap');
const inst = ReactInstanceMap.get(view);
view === inst.getPublicInstance();
It seems I always tend to complicate things...Why wouldn't I handle the touch event in that special view directly?
And I must be blind to not notice a property named _reactInternalInstance to refer to the actual element. Although doing so will breaks encapsulation.

What's the preferred way to go about using backbone with non-crud resources?

New to backbone/marionette, but I believe that I understand how to use backbone when dealing with CRUD/REST; however, consider something like results from a search query. How should one model this? Of course the results likely relate to some model(s), but they are not meant to be tied to said model(s).
Part of me thinks that I should use a collection using a model that doesn't actually sync with a data store through the server, but instead just exists as a means of a modeling a search result object.
Another solution could be to have a collection with no models and just override parse.
I assume that the former is preferred, but again I have no experience with the framework. If there's an alternative/better solution than those listed above, please advise.
I prefer having one object which is responsible for both request and response parsing. It can parse the response to appropriate models and nothing more. I mean - if some of those parsed models are required somewhere in your page, there is something that keeps reference to this wrapper object and takes models from response it requires via wrapper methods.
Another option is to have Radio (https://github.com/marionettejs/backbone.radio) in this wrapper - you will not have to keep wrapper object in different places but call for data via Radio.

Calendar throughout CakePHP site, but CakeBook says to not use a Model in a Component

I have a small calendar widget-type thing on many pages throughout my site. The goal is for it to retrieve events from X category that fall between Y and Z dates.
My assumption (I'm new to CakePHP) was that I should create a component, and have it do the query. Something like this:
class CalendarComponent extends Object {
var $uses = array('Event');
function getEvents($category = null, $date = null, $limit = null) {
$events = $this->Event->find('list', //conditions to get correct events
return $events;
}
}
BUT, according to this CakeBook page:
To access/use a model in a component
is not generally recommended
So - where would I store this logic / model call if not in a component? I've admittedly not used a component yet (or not created one anyway) due to lack of really understanding how I should use them - any snippet of advice on this is also VERY welcome.
Great question in my opinion and I imagine one that comes up quite often. I was actually dealing with a similar problem where I wanted some site-wide data gathering or functionality shoved into a component.
The first thing to keep in mind:
The book is a guideline.
These 'rules' aren't rules. If there's a good reason for breaking the rule and you understand why the rule is being broken then break the damn thing! Cake itself breaks this rule quite often.
Core components that require/use models:
Acl
Auth
Sessions (fairly positive you can save session data to a model)
So, clearly there are use cases where you need to use a model inside a component. How do you do it though?
Well, there's a couple different ways. What I wound up going with? Something like this:
<?php
ModelLoadingComponent extends Object {
public function startup($controller) {
$controller->loadModel('Model');
$this->Model = $controller->Model;
}
}
?>
That's it! Your component is now setup to use $this->Model...just like you would in a controller.
Edit:
Sorry, to clarify: no, you don't have to setup a new component to load models. I was showing an example for how you could load a component in any model. The startup function I used is a component-specific callback, there's a whole slew of them http://book.cakephp.org/view/998/MVC-Class-Access-Within-Components. These callback methods make components a lot easier to work with. I highly recommend looking at this part of the components tutorial if nothing else.
If you were working inside an AppController object you could call $this->loadModel() but we aren't working an AppController! We're working with a component, really an Object. There is no Object::loadModel() so we have to come up with a different way to get that model. This is where $controller comes into play in our startup callback.
When the startup method is invoked by Cake it will pass the $controller object it's working with on this dispatch as the first parameter. With this we're able to access controller methods...like loadModel().
Why do we do it this way?
Well, we could use ClassRegistry::init('Model') in each of our component methods that need to use the model. If you have 10 methods in your component and only 1 of them uses the model this might work. However, what if you have 10 methods in your component and all 10 of them use the model? Well, you'd be calling ClassRegistry::init('Model') 10 times! That's a lot of overhead when what you really want is just 1 model object. With this method the component is creating one model object. The one we create in startup.
I hope this clarifies your questions and provides some insight into why I use this method for models in components.
Edit: Added a code clarification after I did some experimenting.
I think writing a component is overkill in this case and it would be cleaner to put the getEvents method into the Event model.

RIA Services and Relationships in Silverlight 3

I've finally managed to get a handle on loading information using Silverlight, ADO.NET Entities, and RIA Services, but I'm still having a problem with getting the information about the relationships.
For instance, imagine a product, and that product has several categories of attributes. We'll call them ProductAreas.
The Product object has a property called ProductAreas (as a result of their relationship), but when I call:
ctx.Load(GetProductsQuery());
(Where ctx is my DomainContext), the Product objects returned have the ProductAreas property, but it contains no elements, which is a very serious problem, in my case.
So the question is: How do I get access to these relationships?
I'm not sure what your GetProductsQuery() method does, but you should be able use the .Include('ProductAreas') method in your query. If you update your question with the contents of that method I'll try to help more.
This isn't technically the way this system is supposed to work, but I wanted to expand on your answer, while at the same time giving it the credit it rightfully deserves for leading me where I needed to be.
The solutions was to, in the GetProductsQuery() method use
return this.ObjectContext.Products.Include("ProductAreas");
instead of
return this.ObjectContext.Products;
And in the metadata file, go to the Products class and, just above the ProductAreas property add [Include()], so that it looks like:
[Include()]
public EntityCollection<ProductAreas> ProductAreas;

Should a factory method of a custom container return the newly created instance?

I have a custom collection Doohickeys indexed by keys. This collection has a factory method createDoohickey(key) and an accessor Doohickey(key). Should createDoohickey(key) return the new object or should it return void?
In the first case, I would use it like this
myDoohickey = doohickeys.createDoohickey(key);
doStuff(myDoohickey);
in the other case like this
doohickeys.createDoohickey(key);
doStuff(doohickeys(key));
Which one would you consider preferable, and why?
EDIT I believe I have learned quite a bit over the years and that the answer I accepted is actually not really the best one.
I'm not sure the container should have a factory method to create the object it contains - good separation of concerns would be to separate object creation from the container.
Therefore, I think you should have something like this:
Doohickey myDookickey = new Doohickey();
doohickys.Add(key, myDookickey);
doStuff(myDookickey); // or
doStuff(doohickeys(key));
You are then free to use a separate object factory or instantiate Doohickey directly. This makes it easier to unit test the container with mock Doohickey objects.
If you must have the factory method, I would return the Doohickey, because it is probably cheaper to ignore the return value (assuming a reference/pointer is returned) when it is not needed than to use the index to retrieve it when it is.
Yes, a Factory should return the newly created instance.
However like Alex pointed out you could seperate the Repository and the Factory. I would most likely design the factory to have a reference to the repository. I don't think it would be the end of the world of you combined the two into one class just as long as the factory method actually returns the newly created instance.
The example above embeds the factory method in the container class. I agree with willcodejavaforfood, and this may or may not be a good idea over the longer term. The issue is whether the reduced coupling of splitting the factory into its own class is worth the extra cost.
As far as why a factory method should return the newly created instance, it is preferable to decouple creation from containment. Some users of the class might want one but not the other. Also, when you couple creation and containment you can no longer (unit) test creation without also testing containment.
This answer is from a colleague of mine. He suggested to have createDoohickey(key) indeed return the Doohickey; and, additionally, to call it getDoohickey(key) instead.
EDIT I believe after what I have learnt since that this answer is not necessarily the best one any more.

Resources