1

I have method that accept argument of Object type. But inside of method checked if is e.g. List type. Is possible in mockito to stub it? E.g.

public void checkValue(Object arg) {
   if (arg instanceof List) {
    ....

So in mockito:

Object myObject=mock(Object.class);

After I need write something like:

when (myObject instanceof List).thenReturn List

How it can be done? Thanks.

abahgat
  • 13,360
  • 9
  • 35
  • 42
user710818
  • 23,228
  • 58
  • 149
  • 207
  • Doing instanceof in Java is a potential code smell - if you're doing this a lot, then your code isn't very object orientated. – SteveD Sep 07 '11 at 09:40

2 Answers2

5

Sure, you can mock how ever you want. Ex:

Object o = mock(List.class);
3

There is an advice that states

Do not mock types you don't own

So your test should accept an instance of a real list object new ArrayList() instead of a mock.

Should you only mock types you own?

Community
  • 1
  • 1
denis.solonenko
  • 11,645
  • 2
  • 28
  • 23
  • The blanket rule of not mocking what you don't own is ridiculous--there are good cases for mocking your wrapper for an API rather than mocking the API, but there are also plenty of good reasons to mock an API directly. That said, I agree with @denis.solonenko that in cases like this, it's better to just create a List object and pass it in. – Christopher Pickslay Sep 08 '11 at 17:12
  • @chrispix that's why I called it an `advice` not a `rule` :) – denis.solonenko Sep 09 '11 at 01:06