Skip to content

Instantly share code, notes, and snippets.

@bryder
Created September 15, 2016 03:25
Show Gist options
  • Save bryder/a439d7ef2624bc9f53c78c9bba2b734a to your computer and use it in GitHub Desktop.
Save bryder/a439d7ef2624bc9f53c78c9bba2b734a to your computer and use it in GitHub Desktop.
How to mock another service used in a class you are testing when using spring
// http://stackoverflow.com/questions/2457239/injecting-mockito-mocks-into-a-spring-bean
// Given this service somewhere
@Service
public class MyService {
@Autowired
private MyDAO myDAO;
public void someMethod() throws SomeExecption {
}
}
// note tthat my context configuration was a little different
@ContextConfiguration(classes = { MvcConfiguration.class })
@RunWith(SpringJUnit4ClassRunner.class)
public class MyServiceTest {
@Autowired
private MyService myService;
private MyDAO myDAOMock;
@Before
public void before() {
myDAOMock = Mockito.mock(MyDAO.class);
ReflectionTestUtils.setField(myService, "myDAO", myDAOMock);
}
// etc
@Test
public void atest() {
doThrow(new SomeException()).when(myDAOMock).someMethod();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment