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

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.

Related

SONAR Violation IllegalType, why it is important to fix it?

I have noticed in SONAR that I have a violation that is called IllegalType in my java Code. I looked for this and in Checkstyle explain about it this :
Checks that particular class are never used as types in variable declarations, return values or parameters. Includes a pattern check that by default disallows abstract classes.
Rationale: Helps reduce coupling on concrete classes. In addition abstract classes should be thought of a convenience base class implementations of interfaces and as such are not types themselves.
But I don't understand really why is this a problem in my code. If anyone can explain me better maybe with an example it could be great!. Thanks at all.
What Aaron Digulla said in his comments is a good practice for sure. However I also found this IllegalType issue with my own Abstract Classes (instead of interfaces) which don't seem to me to be pretty clear. I understand the benefits of using intefaces insteaf of classes, and I also understand that abstract classes are partially classes (so much more a class than a interface) but I don't see the benefits of this rule, as I can find cases where I can return a concrete class (no abstract) which is a superclass of what I'm actually returning.
Not all violations that Sonar finds are for everyone. The check IllegalType (docs) tries to make sure you don't use classes that most developers deem "broken" in some way like Vector (use ArrayList instead).
Other classes shouldn't be used as a return type. Always return List instead of ArrayList, Set instead of HashSet, Map instead of HashMap - that way, consumers of your code don't know any unnecessary details about your implementation. If you find you need to replace HashMap with TreeMap (or vice versa) in a method, that will be much more simple if you don't have to change all the places as well where this method was called.
Generally, the check isn't a problem as such (your code works) but fixing those will make your code easier to maintain in the future.

Mocking of aggregates with any Java mocking framework

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 :)

How to mock parts of a service and test others?

I'm using easymock, and I am mocking my UserService class.
My UserService has a few methods:
boolean canUserLogin(..);
boolean canUserJoinClass(...);
Now some of the methods call each other, and if I am testing method#1 I want to stub/mock methods #2 and methods# 3 that are called in method#1.
What I am confused is, how can I mock parts of a class and leave others to run the actual code?
So I want to actually test UserService.method#1, but mock UserService.method#2 and UserService.method#3 that method#1 calls internally.
By specifying return values for the methods you want mocked; see the easymock docs for examples.
The "Specifying Return Values" section discusses creating return values for mocked methods.
The "Partial mocking" section (towards the bottom) discusses mocking actual classes.
I agree with the docs (and other answers) that this may be an indication of sketchy design. Without further details, it's hard to say how sketchy it is, if it is at all.
You can check some library like Easymock, but I don't sure whether it can do this.
And here is my solution without third-party library. Create a subclass of UserService, and override the method you want to mock.
class SubUserService{
#override
boolean canUserJoinClass(...){
return false;
}
}
But notice the mock method can't be private.
And if this is one real problem you meet, you should refactor you methods to different classes.
I know Mockito supports "spy" on real objects. I could not find an equivalent in Easy Mock. So, I am not sure if you can do this.
Having said that, this is a smell to me. Why do you need to mock it? Is that an indication of the fact that your object is doing too much and hence you need to mock the other interactions?
Also, whenever you need to worry about the implementation of a method (method 1 in this case) i.e. the fact that it calls method2 and method3, especially of the same class, that sounds to me like a encapsulation leaking.
Mocking is intended to be used for dependencies, so you can test in isolation. In this case, you don't have any dependencies, since the methods you are calling are on one class. So I wouldn't use mocking here.
If methods 2 and 3 are so complicated that you want to mock them when testing method 1, then perhaps you should separate them out into their own class(es), so you can easily mock them.

Extending fluent interface

I'm starting using Fluent Assertions and I like it a lot, but wonder if it's possible to extend the existing tests in a general way like this:
add method hasSizeAtLeast(int limit) in GroupAssert
add method startsWithIgnoringCase(String prefix) in StringAssert
use alternatives like x.either().isIn(someSet).or().isNull()
These are just examples what I could need soon. I can do some workaround for each of them, but then I lose the readability and the easy of use of the fluent interface.
My last example is meant to throw iff both x.isIn(someSet) and x.isNull() do.
Here is a post by the author about opening up his API for extending assertions on already handled types. Lesson #1 in particular discusses the change to un-finalize classes. The post also gives an example of sub-classing StringAssert as MyStringAssert.
However, it looks like you cannot extend classes such as StringAssert in a way that maintains the "fluency" of the API. The StringAssert class isn't final, but still it doesn't allow you to parameterize its type (i.e. the "this" type that's returned by methods in StringAssert itself) in subclasses. For example, let's say you add a method checkFoo in MyStringAssert. As you discovered, the following is invalid because the original StringAssert methods return StringAssert:
new MyStringAssert("abcd").contains("a").checkFoo(); // compile-time error!
You only can call your subclass's methods first, which is valid but kind of lame:
new MyStringAssert("abcd").checkFoo().contains("a"); // compiles
You might consider contacting the author, or even submitting a patch to his git project. A possible solution would be to add the parameterized type back into StringAssert, and also provide the StringAssert concrete type via an anonymous subclass within Assertions.assertThat(String), which is the recommended entry point anyway. Then, everybody else can subclass StringAssert as you described. I haven't tested this suggestion either, but it seems to make sense...

Homegrown utility methods

Static utility methods are generally frowned up by OO purists.
I was wondering however what people feel about utility methods that are used to avoid something simple like a null check throughout the application.
String.trim() throws a NPE when invoked on a null String. So I have to do:
if(str!=null)
setValue(str.trim());
else
setValue("");
What if I create a utility method that checks for the null?
setValue(myTrim(str));
public static String myTrim(String str) {
if(str==null) return ""
else return str.trim();
}
The one problem I have encountered with methods like these is that some developers on the team might not like/not know this utility and might be doing staight calls after doing a null comparison.
Is this something that you do your framework too? If yes, what are the other common utility general use methods that people have created and are using in their applications?
What do you feel are the pros and cons of either approach?
I'd be inclined to replace the homegrown uses when an existing library (like Apache Commons Blah Blah Blah) already has written it. Code you can offload to someone else lets you focus on the important parts of the software that truly differentiate your work from everyone else's. But yes, utility classes with static methods are great, if they need to be written by you at all.
FYI, take a look at StringUtils.trimToEmpty(). Good luck.
some developers on the team might not like/not know this utility
That's what communication is good for. And I don't mean e-mail.
Talks about these kind of functions, probably other team members are doing the same and by not communitating you're duplicating code and efforts.
You may find a way to use these utility methods or even some more experienced developer migth have already develop a more mature lib or used a 3rd party.
But by all means, communicate with your team
I'm not an OO purist. So i love stuff like this. Anything that makes it easier to write code that reflects my intentions without getting bogged down in irrelevant details.
Write it. Use it yourself. Don't be shy - demonstrate how much cleaner it makes your code. Worst case, at least there'll be a bit less repetition in your code...
In terms of a design principle, there are some things that are just more logically static methods. If the utility class that you're writing doesn't really have any "state", and it feels more logical to make it uninstantiable with a bunch of static methods, then do it like that. But make sure your class is genuinely uninstantiable (give it a private constructor; I've seen people declare the class as abstract, but that's no good because people can override it).
The problem that you then get into is that if your class is project-wide, you need to treat it as a library class. And writing libraries is different from writing general code:
in general code, you should profile rather than prematurely optimising; but in a library method, you can't predict how people will use your call in the future;
you need to be very careful to document or clearly name what your method does;
you need to give it generic behaviour, and not be blinded by some specific feature that you need at that moment (e.g. if you have a method to "tokenise a string", what do you do with empty tokens? if you need to ignore them, will other callers to your method?)
I have a few classes that just contain fave static methods - they do make sense to have. You can put together extensive unit tests checking any and all boundary conditions.
In the case you described though - wouldn't it be better to make the setValue method accept any string sent to it? The method could then apply a default null string, trim it or even throw an exception if the value was incorrect.
The JavaDoc on that routine can then clearly state what inputs are valid/invalid and what happens to invalid inputs.
Not saying this is right - just another viewpoint
I use a lot of utility functions. There are some things that just don't need "objects", but I don't like the particular example you have of trim().
A reference to string that is null is very different from an empty string. Unless the app is very simple, and you know you always want to read a null reference as "", I wouldn't do it. For this case, I prefer:
setValue((str != null) ? str.trim() : "")
For me, an uncaught NPE is a good indication that there's a major error going on in the application!

Categories

Resources