Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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

This comment has been minimized.

Copy link

@ptitfred ptitfred commented Apr 11, 2012

Does it work if you manually spy familyController like this:

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

@clakech

This comment has been minimized.

Copy link
Owner Author

@clakech clakech commented Apr 11, 2012

@ptitfred

This comment has been minimized.

Copy link

@ptitfred ptitfred commented Apr 11, 2012

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

@clakech

This comment has been minimized.

Copy link
Owner Author

@clakech clakech commented Apr 11, 2012

Oh really... sh**! Tks btw

@LudoMeurillon

This comment has been minimized.

Copy link

@LudoMeurillon LudoMeurillon commented Apr 11, 2012

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

This comment has been minimized.

Copy link
Owner Author

@clakech clakech commented Apr 11, 2012

@ptitfred

This comment has been minimized.

Copy link

@ptitfred ptitfred commented Apr 11, 2012

Good to know indeed

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