Mocking of aggregates with any Java mocking framework - java

Are there any mocking framework that can do a "full" mocking of every child in an aggregate? For example.
final Report report = createMock(Report.class);
expect(report.getReportSides().get(0).getSideGroup().get(1)).andStubReturn(createSomething());
I want this call with these indices be mocked without me having to do anything else, and before I start to write some massive testing code... is this possible in any framework, EasyMock, PowerMock, Mockito, etc?
(The class example is a legacy class auto-generated from a customers XML, hence the weird class structure, and the absence of domain service layer).

I'm sure you know it's strongly advised to not mock values, but with legacy stuff there could be funky stuff.
Anyway the following declaration might do a great part of the job:
mock(Report.class, RETURNS_DEEP_STUBS)
However you seem to have collections in your aggregate report.getReportSides().get(0).getSideGroup().get(1), and due to type generics erasure Mockito or others frameworks cannot infer the runtime type that should be in the collections, so RETURNS_DEEP_STUBS answer will create a mock matching the return type that is read through reflection, and will certainly be a mock of Object itself in the case of java collections. So you'll have to deal with it manually.
As a side note, there have been progress for generic types in mockito trunk, it can retrieve more generic information that is embedded in the class, it's clearly not near anything that have runtime introspection (impossible with current versions of Java) but it gets closer to it.
With the upgraded RETURNS_DEEP_STUBS you could do :
public interface A<K extends MyKeyType> extends Map<K, MyValueType> {}
deepStubMock.entrySet().iterator().next()
.getValue().someValueTypeMethod().eventuallyFollowedByAnotherMethod();
EDIT : looks like David answered before me in the comment :)

Related

Mocking class with existing class in JMockit (replacement for `redefineMethods`)

I've got two classes as input and want to mock one with the other. That used to be very simple in JMockit, one just called
Mockit.redefineMethods(originalClass, mockingClass);
But in version 0.999 this deprecated method was removed. I need features of a newer version of JMockit, so I cannot use the older versions any more.
I guess from the documentation in the deprecation message that using the proposed "modern" way to do it would be to define a MockUp<originalClass> and use this as the mockingClass.
Unfortunately, I get both values as input parameters at runtime (declared as class<?>), so creating a class is not an option.
Is there any way to emulate what Mockit.redefineMethods() has done before version 0.999, even if it might be not the most elegant solution to address this issue?
EDIT
What I get as input is a Map<Class<?>, Class<?>> mockedClasses of classes to be mocked pointing to classes mocking them. These are then iterated over and passed to Mockit:
for (Map.Entry<Class<?>, Class<?>> entry : mockedClasses.entrySet()) {
Mockit.redefineMethods(entry.getKey(), entry.getValue());
}
After that, the test code is executed, then the mocking is disabled again, using restoreOriginalDefinition() instead of redefineMethods() in a similar way.
Ok, the question is clearer now. And the answer is that there is no way to mock a class with another arbitrary class; you have to define the mock-up class as a subclass of MockUp. The very old Mockit.redefineMethods(Class, Class) (removed from the API 4.5+ years ago) only accepted arbitrary classes because that initial API also supported Java 1.4 for test code (which is no longer supported since 0.999, which required generics and/or annotations).

Using mockito.when without knowing the parameters of the method call

I'm Junit testing a class and had to create some Mockito mock objects. The line of code I'm interested in is this
Mockito.when(emailer.sendEmail(INPUT GOES HERE)).thenReturn(true);
the sendEmail() method of emailer takes in two parameters, and I'm not sure what they will be. Is there a sort of wild card that can be used there to replace the parameters without knowing what they will be?
As mentioned in the question comments.
Matchers.any(ClassName.class), which is usually what you want. In Mockito 1.x, this stands in for any object, regardless of its type, but by receiving a class it will typically avoid the need for a cast. (According to Mockito contributor Brice in an SO comment, this behavior will change in Mockito 2 and beyond, presumably to behave more like isA as any(MyClass.class) would suggest in English.)
Matchers.any(), which will usually require a cast, and isn't a good idea for primitives.
Matchers.anyInt() or Matchers.anyShort() (etc), which are good for primitives.
Matchers.anyString(), because Strings are a common use-case.
Because Mockito extends Matchers, most of these methods will be available on Mockito, but some IDEs have trouble finding static methods across subclasses. You can find all of them by using import static org.mockito.Matchers.*;.
Read more about all of the matchers available to you at the org.mockito.Matchers documentation.
If you run into trouble, or want to learn more about how these wildcards work under the surface, read more here.

Mockito - verify method call according to another objects state

I am currently working my way through he book "Growing Object Oriented Design - guided by tests". The authors are the creators of JMock which is used within the book. Since Mockito currently has the most expressive (readable) API I am using Mockito instead of JMock.
For most examples this worked great so far with much less code. It is interesting though to see how the APIs evolved over the time and frameworks (JMock -> EasyMock -> Mockito) and still base on the same concepts.
Anyway: I need to verify that a mock-method is called at the time when a another objects state has a certain value.
public class TestSomething{
private MyMockedInterface mock;
private States state;
#Test
public void testMethod()
{
// I need something like
when(state.equals(value)).verify(mock).method()
sut.doSomething();
}
}
Unfortunately when(T methodCall) cannot handle object comparison. A assertEquals after sut.something() wont help me here because the state might have changed within doSomething several times.
I am quite sure there must be a way to address this. Would be strange if the old JMock had a feature Mockito doesnt :-) ... I just cant find it.
What you need is something called an Answer - this is an object that wraps a little chunk of code that will run when your method is called. The syntax for using an Answer is described at http://docs.mockito.googlecode.com/hg/latest/org/mockito/Mockito.html#11
In your Answer, you can use asserts to check that the state of the other objects is what you need it to be. Then at the end, you can do your verify, just to ensure that the method was called.

My confusion: reflection in Java

I've just finished reading the chapter of 'Thinking in Java' concerning type information and reflection. While instanceof seems quite natural to me, some examples of reflection made me confused. I want to know if reflection is widely used in Java projects? What are 'the good parts' of reflection? Can you suggest any interesting lectures about reflection and type information with more good and worthy examples?
Edit (one more question):
Why is it useful to access private methods and fields withjava.lang.reflect.Method.setAccesible()?
Thanks in advance.
if you could post some of the examples I would be glad to explain it for you.
Reflection is wildly used with frameworks that need to extract meta-info about the running object (e.g. frameworks which depends on Annotations or the fields in your objets, think about Hibernate, Spring and a lot others).
On a higher layer, I sometimes use reflection to provide generic functionality (e.g. to encode every String in an object, emulate Duck Typing and such).
I know that you already read a book which covers the basics about reflection, but I need to point Sun (erm.. Oracle) official Tutorial as a must read: http://download.oracle.com/javase/tutorial/reflect/
One good example in my opinion is instantiating objects based on class names that are known only at runtime, for example contained in a configuration file.
You will still need to know a common interface to the classes you're dynamically instantiating, so you have something to cast them too. But this lets a configuration drive which implementation will be used.
Another example could be when you have to cast an object to a class that it's a descendant. If you are not sure about the type of that object, you can use instanceof to assure that the cast will be correct at runtime avoiding a class cast exception.
An example:
public void actionPerformed (ActionEvent e){
Object obj = e.getSource();
if (obj instanceof objType)
objType t = (objType) obj; // you can check the type using instanceof if you are not sure about obj class at runtime
}
The reason to provide such features in Reflection is due to multiple situations where tool/application needs meta information of class, variables, methods. For example:-
IDEs using auto completion functionality to get method names and attribute names.
Tomcat web container to forward the request to correct module by parsing their web.xml files and request URI.
JUnit uses reflection to enumerate all methods in a class; assuming either testXXX named methods as test methods or methods annoted by #Test.
To read full article about reflection you can check http://modernpathshala.com/Forum/Thread/Interview/308/give-some-examples-where-reflection-is-used

What's the conception behind: Type - Element - Mirror

I'm working with Java 6's annotation processing, i.e. what can be found within javax.annotation.processing (not Java 5's APT).
I wonder what the conceptional difference between the various Element, Type, and Mirror classes is. As I don't really understand this, it's hard to efficiently program an annotation processor. There are various methods that 'convert' between these notions but I'm not really sure what I'm doing when using them.
So, for example, let me have an instance of AnnotationMirror.
When I call getAnnotationType() I get an instance of DeclaredType (which implements TypeMirror for whatever reason).
Then I can call asElement() on this one and obtain an instance of Element.
What has happened?
There is indeed on overlap between these concepts.
Element models the static structure of the program, ie packages, classes, methods and variables. Just think of all you see in the package explorer of Eclipse.
Type models the statically defined type constraints of the program, ie types, generic type parameters, generic type wildcards. Just think of everything that is part of Java's type declarations.
Mirror is an alternative concept to reflection by Gilad Bracha and Dave Ungar initially developed for Self, a prototype-based Smalltalk dialect. The basic idea is to separate queries about the structure of code (and also runtime manipulation of the structure, alas not available in Java) from the domain objects. So to query an object about its methods, instead of calling #getClass you would ask the system for a mirror through which you can see the reflection of the object. Thanks to that separation you can also mirror on classes that are not loaded (as is the case during annotation processing) or even classes in a remote image. For example V8 (Google's Javascript engine) uses mirrors for debugging Javascript code that runs in another object space.
This paper may help understanding the design of Java 6 annotation processing:
Gilad Bracha and David Ungar. Mirrors:
Design Principles for Meta-level
Facilities of Object-Oriented
Programming Languages. In Proc. of
the ACM Conf. on Object-Oriented
Programming, Systems, Languages and
Applications, October 2004.
The object of type javax.lang.model.element.AnnotationMirror represents an annotation in your code.
The declared type represents the annotation class.
Its element is the generic class (see http://java.sun.com/javase/6/docs/api/javax/lang/model/element/TypeElement.html for more information on that matter). The element might be the generic version of a class, like List, where as the declared type is the parametrized version, for instance List<String>. However I'm not sure it is possible to have annotations classes use generics and thus the distinction might be irrelevant in that context.
For instance lets say you have the following JUnit4 method:
#Test(expected = MyException.class)
public void myTest() {
// do some tests on some class...
}
The AnnotationMirror represents #Test(expected = NullPointerException.class). The declared type is the org.junit.Test class. The element is more or less the same as there are no generics involved.

Categories

Resources