test if collection contains 2 objects in any order with equals - spring-boot

What is the best way to test in JUnit that a collection contains two complex objects?
I know that there is containsInAnyOrder(), but I have no control over the objects, as they are created via a REST API and stored in a database. I need them to be compared by equals, not by reference.
Alternatively, it would be sufficient if I can test whether some of their attributes equal, but since the method the test covers involves AsyncCircuitBreakers, I'm not sure of the order.
How can I make sure, the two objects are created in the database with the data I have in mind?

assertThat(Arrays.asList(array), hasItems(yourItem1, yourItem2));
Don't forget to add equals and hashCode methods to implement in your item class. hasItem is a hamcrest method.

Related

What is the name of the design pattern to avoid chained field access?

There is a pattern or term that is used to avoid codes like
myObject.fieldA.fieldB.fieldC
something like this. I forgot what this term is called. Can anyone let me know about it?
It violates the Law of Demeter, which states that code should only access its own local variables, parameters, and instance members.
It could be a case of of feature envy, where a class calls a lot of getters or accesses a lot of data from another class.
If these are really fields, they are poorly encapsulated (i.e., not behind a function), and any change to these fields forces you to modify all code that's using them.
Testing such code becomes hard, as you will have to mock not only fieldA, but also that's fieldB, and in turn that's fieldC.
I think you are trying to create a new object and add certain properties to that object. If that is the case then it's Builder design patten where you seperate the construction and representation.
If you are trying to call a certain field with the above shown code then your design is very poor. An object should store only it's own properties.

How to disable sorting for - allObjects in NSMutableSet?

In my OSX app I have NSMutableSet that contains custom objects. I implemented -isEqual and -hash methods in my custom object classes, so that the set can do comparison the way I want.
However, whenever I insert a new object into my set and then call -allObjects, the array that is returned has the objects in a sorted order.
The order depends on the value of the property that I'm using for comparison of my custom objects in -isEqual method mentioned above.
In my case, I want to preserve the order at which the objects were added to the set.
Does anyone have any clue how to achieve that?
Any kind of help is highly appreciated!
Sets don't have an order, they are specifically designed to be unordered collections. When you call allObjects to get an array, the order you get is not defined so you should not depend on it.
You have 2 basic options here if you want to keep using sets.
Order the array manually once you get it.
Use an NSOrderedSet which maintains order.
In my case, I want to preserve the order at which the objects were added to the set.
Then don't use a set, but an NSArray.
Arrays store their objects in an order, sets do not.

Linq To Sql Where does not call overridden Equals

I'm currently working on a project where I'm going to do a lot of comparison of similar non-database (service layer objects for this discuss) objects and objects retrieved from the database via LinqToSql. For the sake of this discussion, assume I have a service layer Product object with a string field that is represented in the database. However, in the database, there is also a primary key Id that is not represented in the service layer.
Accordingly (as I often do for unit testing etc), I overrode Equals(Object), Equals(Product), and GetHashCode and implemented IEquatable with the expectation that I would be able to write code like this:
myContext.Products.Where(p => p.Equals(passedInProduct).SingleOrDefault();
And so forth.
The Equals override is tested and works. The objects are mutable so the usual caveats apply to the GetHashCode override. However, for the purposes of this example, the objects are not modified except by LtS and could be made readonly.
Here's the simple test:
Create a test object in memory and commit to the LtS context. By committing, the test object is populated with a few auto-generated fields.
Create another identical test object in memory (separate reference)
Attempt to retrieve the first object from the database using the second object as the criteria. (see code line above).
// Setup
string productDesc = "12A";
Product testProduct1 = _CreateTestProductInDatabase(productDesc);
Product testProduct2 = _CreateTestProduct(productDesc);
// check setup
Product retrievedProduct1 = ProductRepo.Retrieve(testProduct1);
//Assert.IsNotNull(retrievedProduct1);
// execute - try to retrieve the 'equivalent' product object
Product retrievedProduct2 = ProductRepo.Retrieve(testProduct2);
A simplified version of Retrieve (cruft removed is just parameter checks etc):
using (var dbContext = new ProductDataContext()) {
Product retrievedProduct = dbContext.Products
.Where(p => p.Equals(product)).SingleOrDefault();
NB: The overridden Equals method knows not to care about the auto-generated fields from the database and only looks at the string that is represented in the service layer.
Here's what I observed:
Retrieve on testProduct1 succeeds (no surprise, equal by reference)
Retrieve on testProduct2 fails (null)
The overridden Equals method called in the Retrieve method is never hit during either Retrieve calls
However, the overridden Equals method is called multiple times by the context on SubmitChanges (called when creating the first test object in the database) (works as expected).
Statically, the compiler knows that the type of the objects being emitted and is able to resolve the type.
So my specific questions:
Am I trying to do something ill-advised? Seems like a straightforward use of Equals.
Corollary to first question: alternate suggestions to deal with linq to sql equality checking while keeping comparison details inside the objects rather than the repository
Why might I have observed the Equals method being resolved in SubmitChanges but not in the Where clause?
I'm as much interested in understanding as making my Equals calls work. But I also would love to learn how to make this 'pattern' work rather than just understand why it appears to be an 'anti-pattern' in the contest of LtS and C#.
Please don't suggest I just filter directly on the context with Where statements. Obviously, I can remove the Equals call and do that. However, some of the other objects (not presented here) are large and a bit complicated. For the sake of maintenance and clarity, I want to keep knowledge of how to compare itself to another of its own type in one place and ideally as part of the object in question.
Some other things I tried that didn't change the behavior:
Overloaded and used == instead
Casting the lambda variable to the type p => (Product)p
Getting an IQueryable object first and calling Equals in the Where clause
Some other things I tried that didn't work:
Creating a static ProductEquals(Product first, Product second) method: System.NotSupportedException:has no supported translation to SQL.
Thanks StackOverflow contributors!
Re Possible dups: I've read ~10 other questions. I'd love a pointer to an exact duplicate but most don't seem to directly address what seems to be an oddity of LinqToSql.
Am I trying to do something ill-advised?
Absolutely. Consider what LINQ to SQL does: it creates a SQL representation of your query. It doesn't know what your overridden Equals method does, so can't translate that logic into SQL.
Corollary to first question: alternate suggestions to deal with linq to sql equality checking while keeping comparison details inside the objects rather than the repository
You'd need to do something with expression trees to represent the equality that way - and then build those expression trees up into a full query. It won't be fun, but it should be possible. It will affect how you build all your queries though.
I would have expected most database representations to be ID-based though, so you should be able to just compare IDs for equality. Usually when I've seen attempts to really model data in an OO fashion but store it in a database, the leakiness of the abstraction has caused a lot of pain.
Why might I have observed the Equals method being resolved in SubmitChanges but not in the Where clause?
Presumably SubmitChanges is working against a set of in-memory objects to work out what's changed - it doesn't have to do any conversion to SQL to do that part.

Join Two Objects for Custom Serialization?

In C# on Framework 4, I have a List and List. They can be joined on the JoinId property. ParentObj will have 2 ChildObj matches, sometimes 10.
I would like to take each Parent and all Children and serialize to a single XML entity. I am having a hard time figuring out where to start, because I also need to serialize the objects in a custom way. Can I use Linq-to-XML in this case to get each object written correctly? XmlSerializer? Not sure.
Thanks.
Can I use Linq-to-XML in this case to get each object written correctly?
Yes. This is exactly what you need. A basic example.
XmlSerializer?
This will work too, but this approach is older and I think it is less appropriate and more complicated in this case.

Validate a Collection Has at Least One Item using Validation Application Block

Using the Enterprise Library 4.1 Validation Application Block, how can I validate that a collection property contains at least one item?
I'm assuming you mean out of the box. If so, then I don't think there is way to validate directly the number of items in a collection.
These are some other ways that you could try:
Decree that you only deal with null collections and not empty collections and use a Not Null Validator. Not practical, though.
Use self validation and have the object validate in code that the collection(s) have the correct number of items. Will work but it's nice to have the validation in the configuration file.
Expose the collection count as a property. This could be done, assuming an employee collection for example, with an EmployeeCount property on your object that contains the collection or you could create your own custom collections that expose a count property. Then you could use a Range Validator to validate on the Count property.
Create a custom validator that can validate the number of items in a collection -- something like CollectionCountRangeValidator.
If I wanted to develop something quickly, I would probably go with option 3. However, option 4 fits in well with the Enterprise Library approach and also allows your class design to be independent of the validation requirements. Plus you could always reuse it on your next project. :) And does anyone really miss creating their own collections when a List will do nicely?
This is already implemented in the EntLib Contrib.
This is called CollectionCountValidator.

Resources