Skip to content

Instantly share code, notes, and snippets.

@clakech
Created April 11, 2012 07:49
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save clakech/2357686 to your computer and use it in GitHub Desktop.
Save clakech/2357686 to your computer and use it in GitHub Desktop.
Why Mockito @SPY and @mock doesn't work together ?
package com.bla.web.controller;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.mockito.Spy;
import org.mockito.runners.MockitoJUnitRunner;
import com.bla.web.dto.FamilyAndItems;
import com.bla.web.service.FamilyServiceImpl;
import static org.mockito.BDDMockito.given;
import static org.mockito.Matchers.anyString;
import static org.fest.assertions.Assertions.assertThat;
@RunWith(MockitoJUnitRunner.class)
public class SpyAndMockFailTest {
@Mock
FamilyServiceImpl familyService;
@Spy
FamilyController familyController = new FamilyController(familyService);
@Test
public void shouldGetFamilyAndItems() {
// given
given(familyService.getFamilyAndItems(anyString())).willReturn(null);
// when
FamilyAndItems familyAndItems = familyController.getFamilyAndItems("id");
// then
assertThat(familyAndItems).isEqualTo(null);
}
}
@ptitfred
Copy link

Does it work if you manually spy familyController like this:

@before
public void setup() {
familyController = Mockito.spy(new FamilyController(familyService));
}

@clakech
Copy link
Author

clakech commented Apr 11, 2012 via email

@ptitfred
Copy link

This is probably a matter of fields ordering in compiled class ; I've observed subtle changes on that topic since jdk7

@clakech
Copy link
Author

clakech commented Apr 11, 2012

Oh really... sh**! Tks btw

@LudoMeurillon
Copy link

You can use Annotations together introducing @Injectmocks (see my fork : https://gist.github.com/2358140)

documentation of @Injectmocks and the way it injects @Mocks into @SPY objets or not-mockito objects http://docs.mockito.googlecode.com/hg/1.9.0/org/mockito/InjectMocks.html

@clakech
Copy link
Author

clakech commented Apr 11, 2012 via email

@ptitfred
Copy link

Good to know indeed

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment