Spring + TestNG + @Spy Example



@ContextConfiguration({"/spring/applicationContext.xml"})
public class SprintTestngWithSpyAnnotationITCase extends AbstractTestNGSpringContextTests {

    //this bean will take mocked objects injected into it, but it itself is not going to be mocked
    @InjectMocks
    @Resource
    SomeService someService;

    //it equals to one that is created via spy(applicationContext.getBean(SomeDAO.class)) and it will be
    // injected to "someService" above
    @Spy
    @Resource
    SomeDAO someDAO;


    @BeforeMethod
    public void beforeMethod() {
        /**
         * Do the spy(someDAO) and inject spied objects to someService . 
* Note that If you put initMocks() inside @BeforeTest, then someDAO will be created with its * constructor instead of spring spawning because during @BeforeTest the application context is * still null *
* * This thing will also do reset() inside it so you don't have to call reset() explicitly */ MockitoAnnotations.initMocks(this); } @Test public void testServe_BehaviorChanged() { Mockito.doReturn("New Value").when(someDAO).access(); Assert.assertEquals(someService.serve(), "New Value"); } @Test (dependsOnMethods = "testServe_BehaviorChanged" ) public void testServe_BehaviorNotChanged() { Assert.assertEquals(someService.serve(), "Original Value"); } }

Leave a Comment

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.