How can I populate an instance of an object with random values? - autofixture

Is there any way I can give AutoFixture an instance of an object and have it go through all the setters and set random data? The wiki examples only show how to obtain an instance from AutoFixture, e.g.
var autoGeneratedClass = fixture.Create<ComplexParent>();
My example use case is a factory method which generate instances of objects with dynamic properties based on a configuration. I want to test that my methods correctly, detect and interact (e.g. copy) these dynamic properties.
dynamic dynamicPropertyObject1 = factoryMethod(configuration);
dynamic dynamicPropertyObject2 = factoryMethod(configuration);
dynamicPropertyObject1.propA = random.Next();
dynamicPropertyObject1.CopyTo(dynamicPropertyObject2);
Assert.That(dynamicPropertyObject2.propA, Is.EqualTo(dynamicPropertyObject1.propA);
Thanks

AutoFixture has a lot of built-in heuristics for creating objects, including some for factory methods.
If AutoFixture finds no public constructors on a type, it starts to look for factory methods; i.e. static methods that return objects of the type of the class that defines that static method, e.g.
public class Foo
{
public static Foo CreateFoo();
// ... other members
}
If, on the other hand, a factory method exists on another class, you'll need to help AutoFixture a bit. The easiest way would be to use the Customize method:
fixture.Customize<Foo>(c => c
.FromFactory(() => FooFactory.CreateFoo())
.WithAutoProperties());
When you subsequently ask a Fixture object for a Foo object, FooFactory.CreateFoo() will be invoked, and because of WithAutoProperties that object will be populated with data created by AutoFixture.

Related

How to mock an array containing objects using mockito?

In my Mockito unit test I am trying to mock an array containing instances of the object Message. To do this I try to mock it like normal objects so like:
private var messagesMock = mock(Array<Message>::class.java)
This gives the following error/exception:
org.mockito.exceptions.base.MockitoException:
Cannot mock/spy class [Lrobot.fsrt.robotguest.common.data.Message;
Mockito cannot mock/spy because :
- VM does not not support modification of given type
How to mock an array the right way using Mockito?
A distinct non-answer: you (almost) never mock objects that represent containers!
An array is just that: a container.
You create the container with the size you need, and then you put your mocked objects into that ordinary container, and make sure that container with your prepared content gets used by your production code.
It is as simple as that: you don't mock arrays, or lists, or maps: you create them as is, and manipulate their content!

Shallow copy of object referenced array

I want to implement the ICloneable.Clone() function.
My class has some primitive members but also an array of referenced objects.
In this referenced object class, I don´t want to implement this function too, so I´m wondering if it is easily possible to do sth like MemberWise Clone from outside.
Public Function Clone() As Object Implements ICloneable.Clone
Return Me.MemberwiseClone
End Function
I have found sth like Array.Clone, but this only works for primitive Types?
You're almost there.
Public Function Clone() As Object Implements ICloneable.Clone
Dim copy = Me.MemberwiseClone
copy.SomeArray = copy.SomeArray.Select(Function(r) r.Clone).ToArray()
Return copy
End Function
Note that since MemberwiseClone is protected, you can't call MemberwiseClone on the objects in the array if those objects are not part of the same inheritance hierarchy as the object implementing this function.

Immutable data model for an WPF application with MVVM implementation

I have an application which has a data tree as a databackend. To implement the the MVVM pattern I have a logic layer of classes which encapsulate the data tree. Therefore the logic also is arranged in a tree. If the input is in a valid state the data should be copied to a second thread which works as a double buffer of the last valid state. Therefore one way would be cloning.
Another approach would be to implement the complete data backend to be immutable. This would imply to rebuild the whole data tree if something new is entered. My question is, is there a practical way to do this? I'm stuck at the point where I have to reassign the data tree efficently to the logic layer.
**UPDATE - Some Code
What we are doing is to abstract hardware devices which we use to run our experiments. Therefore we defined classes like "chassis, sequence, card, channel, step". Those build a tree structure like this:
Chassis
/ \
Sequence1 Sequence2
/ | \
Card1 Card2 Card3
/ \
Channel1 Channel2
/ \
Step1 Step2
In code it looks like this:
public class Chassis{
readonly var List<Sequence> Sequences = new List<Sequence>();
}
public class Sequence{
readonly var List<Card> Cards = new List<Card>();
}
and so on. Of course each class has some more properties but those are easy to handle. My Problem now is that List is a mutable object. I can call List.Add() and it changed. Ok there is a ReadOnlyList but I'm not sure if it implements the immutability the right way. Right as in copy by value not reference and not just blocking to write to it by blocking the set methods.
The next problem is that the amount of sequences and step can vary. For this reason I need an atomic exchange of list elements.
At the moment I don't have any more code as I'm still thinking if this way would help me and if it is possible at all to implement it in a reasonable amount of time.
Note that there are new immutable collections for .NET that could help you achieve your goal.
Be very cautious about Dave Turvey's statement (I would downvote/comment if I could):
If you are looking to implement an immutable list you could try storing the list as a private member but exposing a public IEnumerable<>
This is incorrect. The private member could still be changed by its container class. The public member could be cast to List<T>, IList<T>, or ICollection<T> without throwing an exception. Thus anything that depends on the immutability of the public IEnumerable<T> could break.
I'm not sure if I understand 100% what you're asking. It sounds like you have a tree of objects in a particular state and you want to perform some processing on a copy of that without modifying the original object state. You should look into cloning via a "Deep Copy". This question should get you started.
If you are looking to implement an immutable list you could try storing the list as a private member but exposing a public IEnumerable<>
public class Chassis
{
List<Sequence> _sequences = new List<Sequence>();
public IEnumerable<Sequence> Sequences { get { return _sequences; } }
}
18/04/13 Update in response to Brandon Bonds comments
The library linked in Brandon Bonds answer is certainly interesting and offers advantages over IEnumerable<>. In many cases it is probably a better solution. However, there are a couple of caveats that you should be aware of if you use this library.
As of 18/04/2013 This is a beta library. It is obviously still in development and may not be ready for production use. For example, The code sample for list creation in the linked article doesn't work in the current nuget package.
This is a .net 4.5 library. so it will not be suitable for programs targeting an older framework.
It does not guarantee immutability of objects contained in the collections only of the collection itself. It is possible to modify objects in an immutable list You will still need to consider a deep copy for copying collections.
This is addressed in the FAQ at the end of the article
Q: Can I only store immutable data in these immutable collections?
A: You can store all types of data in these collections. The only immutable aspect is the collections themselves, not the items they contain.
In addition the following code sample illustrates this point (using version 1.0.8-beta)
class Data
{
public int Value { get; set; }
}
class Program
{
static void Main(string[] args)
{
var test = ImmutableList.Create<Data>();
test = test.Add(new Data { Value = 1 });
Console.WriteLine(test[0].Value);
test[0].Value = 2;
Console.WriteLine(test[0].Value);
Console.ReadKey();
}
}
This code will allow modification of the Data object and output
1
2
Here are a couple of articles for further reading on this topic
Read only, frozen, and immutable collections
Immutability in C# Part One: Kinds of Immutability

C# - Pass a struct to a form by reference and return value?

I have a struct:
struct Order
{
public string orderNumber;
public string orderDetail;
}
I then assign some values in Form1 and try to pass them by reference (ref) to Form2:
(Form1)
Order order = new Order();
order.orderNumber = "1234";
order.orderDetail = "Widgets";
Form2 frm2 = new Form2(ref order);
Is it possible to store the values in Form2 so that when Form2 is completed processing the values it will return the updated struct values to Form1?
In this scenario there would be a button that would close the form after validating the data.
One pattern that's sometimes useful is to define a class something like:
class Holder<T> {public T value;}
Such a class makes it possible to pass and mutate value types with code that requires reference types. Using such an approach, a routine which accepted a structure by reference and was supposed to pop up a modal dialog and fill in the structure from it, could create a Holder<thatStructType>, pass that to the form, and then copy the data from that Holder back to the passed-in reference. While in your particular scenario, it may be better to have the data-holding thing simply be a class, structures have the advantage that one can know that no outstanding references to them exist; if a routine declares a structure and passes it by reference to some outside code, then once that code returns the values in that structure won't change unless or until the routine writes them itself or passes the structure by reference to some other code. By contrast, if a routine exposes a class reference to outside code, there's no telling what that code may do with it.
Incidentally, the Holder class is also useful in a number of other scenarios. For example, if one has a Dictionary<String, Holder<Integer>> myDict, one may use Threading.Interlocked.Increment(myDict(myKey).Value)) to perform a thread-safe increment of the indicated item, much more efficiently than would be possible with a Dictionary<String, Integer>.
What I think you're asking is if Form2 can store a reference to the order structure that was passed in the constructor. The answer is no. If you want to store references, use a reference type (a class).

why would I want a method that needs an instance?

Why would I want a method that needs an instance? Why wouldn't I make all my methods static?
Why would you not want any state anywhere in your program?
Can you imagine if there were no String instances, and everything on String was static? How would you represent two distinct sequences of characters? Now apply the same logic to other code.
Fundamentally, OO languages are built around the idea of objects with state: one instance of Book isn't the same an another instance of Book - each Book instance encapsulates its name, author, publication date etc. How would you model that with only static methods, and no instances?
Of course you could make all your methods static and pass in a Book as the first parameter on each call that needed to use the state. Behind the scenes, something pretty much like that is already happening... except you've then lost polymorphism, so interfaces, abstract classes etc are useless. Not good.
Because objects are state and behavior together, encapsulated into a single component.
If you have individual instances, it means they can each have private data that varies from instance to instance.
Static data and methods are shared at the class level. Individual instances cannot have different static data.
Static methods can't directly access the member variables within an object - they can only access static variables.
If you had a car class and a static data member like an integer in it, you could only ever have one car because you cant make multiple instances of cars and get multiple instances of that variable - you'd only ever have the single static one.
Every car can't have the same license plate number, thus ever car needs its own license plate variable.
The methods in the class that work with that variable need to be non-static to work on it directly then.
Using the example of a "Car" class, you might have a method called "startCar()". Obviously, you want this method to interact only with a particular "instance" of a car and not be global to ALL your cars. Example in Java:
public class Car {
public void startCar() {
// code to start car
}
}
public class MyProgram {
public static void main(String[] Args) {
Car myFord = new Car();
Car myOpel = new Car();
myCar.startCar; // starts the Car "myCar" and leaves "myOpel" alone
}
}
It's also worth noting that Static Methods may not make use of Instance Variables of the class in which they are defined.

Resources