validating a complex object in a jmock - jmock

I've coded a custom jmock action that just stores away a complicated bean, and then later on I use conventional JUnit assertions to validate it.
Is there a straightforward means in JMock expectations to assert the values returned from several getters called on an object passed to a function of the mocked interface?

I'm not sure that goes with the grain of JMock design. For the record, you can combine multiple matchers for a single object with allOf()
oneOf(foo).wasCalled(with(allOf(hasProperty("bar", equalTo(1)),
hasProperty("fizz", stringContains("buzz"))));
that's a bit ugly, so I usually package up the construction of the expectation in a helper method

Related

What are the uses of constructor reference in java 8

I was reading about Java 8 features, which lead me to this article and I was wondering about the actual uses of constructor reference, I mean why not just use new Obj ?
P.S, I tried googling, but I failed to find something meaningful, if someone has a code example, link or tut it will be great
First of all, you should understand that constructor references are just a special form of method references. The point about method references is that they do not invoke the referenced method but provide a way to define a function which will invoke the method when being evaluated.
The linked article’s examples might not look that useful but that’s the general problem of short self-contained example code. It’s just the same as with the “hello world” program. It’s not more useful than typing the text “hello world” directly into the console but it’s not meant to be anyway. It’s purpose is to demonstrate the programming language.
As assylias has shown, there are use cases involving already existing functional interfaces using the JFC API.
Regarding the usefulness of a custom functional interface that’ll be used together with a constructor reference, you have to think about the reason to use (functional) interface in general: abstraction.
Since the purpose of an interface is to abstract the underlying operation, the use cases are the places where you do not want to perform an unconditional new SomeType(…) operation.
So one example is the commonly known Factory pattern where you define an interface to construct an object and implementing the factory via constructor reference is only one option out of the infinite possibilities.
Another important point are all kinds of Generic methods where the possibility to construct instances of the type, that is not known due to type erasure, is needed. They can be implemented via a function which is passed as parameter and whether one of the existing functional interfaces fits or a custom one is needed simply depends on the required number and types of parameters.
It's useful when you need to provide a constructor as a supplier or a function. Examples:
List<String> filtered = stringList.stream()
.filter(s -> !s.isEmpty())
.collect(Collectors.toCollection(ArrayList::new)); //() -> new ArrayList<> ()
Map<String, BigDecimal> numbersMap = new HashMap<>();
numbersMap.computeIfAbsent("2", BigDecimal::new); // s -> new BigDecimal(s)
someStream.toArray(Object[]::new); // i -> new Object[i]
etc.

What are the downsides of "typing" your control state?

I am relatively new to Web Parts and Web Forms (I have only worked a lot with the MVC framework).
I am planning to store some data in the control state. All the examples I can find put an object[] array in the control state and the base control state on the 0 index.
I don't really like putting everything in an object[], so I wanted to create an extra class for my web part with typed properties: e.g. MyWebPartControlState. I will store the base control state in a property BaseControlState of type object.
I was wondering if this could cause any problems or if there are any other reasons why this might not be a good idea. I am wondering because it feels logical to me, but I cannot find any examples of control state where they don't put everything in the control state directly or in a object[].
Thanks in advance.
The control state is persisted in the same field as view state and follows the same rules for serialization. All the samples you found use an object array because that's one of the types the optimized state serializer in ASP.NET understands and for which is able to optimize serialization.
If you use a custom object the serializer won't use the optimizations and instead will serialize your object using the BinaryFormatter which will lead to bloated control state. If you want to have a strongly typed view of your state you should implement IStateManager on your custom class so that it encapsulates the transformation of itself from and to simple objects that the serializer understands.
If I recall correctly the serializer can efficiently serialize the following types:
Primitive types (int, long, etc);
DateTime;
string;
Boxed values of supported value types;
Object arrays containing instances of supported types;
Pair and Triplet objects containing instances of supported types.
I wrote a short blogpost illustrating the differences in size resulting from a simple custom class being serialized with BinaryFormatter versus implementing IStateManager and decomposing to simple types that the serializer can optimize. You can find it at:
ASP.NET ViewState Tips and Tricks #2

What is main advantage of Tuple?

Can anyone tell me what is the main advantage of using tuple? In what scenarios do I need to use these?
I assume that you're talking about the Tuple<> type and not anonymous tuple classes.
Like an anonymous type, Tuple<> allows you to avoid declaring a new class just to group a few objects. Unlike anonymous types, tuple types have known names and thus can be used as method return and parameter values, etc.
Personally, I try to avoid heavy use of Tuple<> because it can make for difficult to understand code, expecially when used with primitive types (e. g. if you see a Tuple it's not obvious what each field represents).
One place I have found tuples to be very useful is as dictionary keys. Because Tuples implement Equals() and GetHashCode() (not ==, though!), they are perfect for things like private dictionaries that cache information based on a compound key.
It's used mostly to avoid declaring a class / struct with a few properties only for the sake of passing a group of objects around, where only one object can be passed.
Lets say I have a list of urls to go through and if i get an error (4xx or 5xx) I want to build a list and then either later display it to the user or just look at it in my debugger.
I'd catch the web exception and have a Tuple<string, int> (url, http error code) instead of creating a struct for one or two functions to use. Heck it might even be a foreach loop with a breakpoint on if the list has more then 0 items. Thats when it is useful.

can I use Moq to grab values that are passed into a public method of an object that is not a mock?

I'm writing a unit test for FluentMigrator. I am testing a method that gets called n times in succession. What I'd like to do is grab the successive inputs and stow them in a SortedList, so that I can verify the methods were called in the right order, then pass those inputs to the actual method -- like a temporary redirect. But, after reading the docs etc, I can't get it to work.
Code in the test:
var listOfVersions = new SortedList<int, long>();
int i = 0;
var runnerMock = Mock.Get(_runner); // runner is a MigrationRunner
runnerMock.Setup(r => r.RollbackToVersion(2))
.Callback((long v) =>
{
listOfVersions.Add(i, v);
i++;
_runner.RollbackToVersion(v, true); });
_runner.RollbackToVersion(2);
The error:
System.ArgumentException : Object instance was not created by Moq.
Parameter name: mocked
I'm coming from Moles, where dipping into the behavior of an object and then redirecting it isn't unusual. Maybe it is in Moq?
No. Really mocking frameworks fall into 2 camps. The ones that can mock anything and the other than can only mock Interfaces, Abstract/Virtual methods.
This is because they use very much a different interception technology. Moq, RhinoMocks etc use Castle's Dynamic Proxy Generator under the hood which all it does create an instance that exposes the same public interface. It uses this to record interactions with that object so you can verify on it. Abstract and Virtual members can be mocked cause it can derive from that class and prevent calls to the base class.
However Moles and TypeMock Isloator play around with the IL directly. I know for TypeMock it actually weaves IL into the methods you are trying to mock so you can intercept and record interactions on it for testing (It also stops further processing of the methods also). I know that Moles creates another assembly and you refer to that in your test method but I imagine it does very similar things to TypeMock.
If you want to mock concrete non overrideable methods you will have to use that latter frameworks.

Why is object returned from getDefinitionByName()?

In Actionscript 3, why does getDefinitionByName() return an Object when the docs say:
Returns a reference to the class object of the class specified by the name parameter.
Based on that, I would conclude that the returned object should be Class instead of Object. Can someone enlighten me why that is not the case?
getDefinitionByName can also return a Function, such as getDefinitionByName('flash.utils.getDefinitionByName').
This only works on namespace-level functions, though, not static class methods.
Despite the method signature, getDefinitionByName does return Class. I think the misleading signature is due to the method existing before the Class object (when it used to return an anonymous/extended object instance).
Perhaps Adobe considered that this function might return different values in a future version of Flash Player. For instance, ECMAScript, the standard on which ActionScript is based, has historically used Function objects with prototypes as the basis for class-like objects. During discussions of the newest versions of the ECMAScript standard, there has been sugestions for "freezing" function-based classes at run-time to make them into something like compile-time Class objects. What if you could also specify a definition name for them? Are they actually of type Class at this point, or are they still or type Function? Probably the later, in my opinion. Both 'Class' and 'Function' references can be generalized as Object, so that return type makes sense in this context.
Note: This explanation is purely speculation based on what I've read in the ECMAScript specification wiki and the blogs of various committee members.

Resources