Created
September 15, 2016 03:25
-
-
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
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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