1
public interface Dummy {
    public returnSomething doDummyWork(arg1, agr2);
}

public class A implements Dummy {
    @AutoWired
    PrintTaskExecutor printTaskExecutor;

    public returnSomething doDummyWork(arg1, agr2) {
        callingVoidMethod();
        return something;
    }

    public void callingVoidMethod() {
        printTaskExecutor.printSomething(arg1, arg2);
    }
}

public class testDummy {
    @Autowired
    Dummy dummyA//this bean is configured in ApplicationContext.xml and it works fine.
    @Mock
    PrintTaskExecutor printaskExecutor;

    @Before
    public void initMocks() {
        MockitoAnnotations.initMocks(this);
        printaskExecutor = Mockito.mock(PrintTaskExecutor.class);
        Mockito.doNothing().when(printaskExecutor).printSomething(anyString(), anyString());
    }

    @Test
    Public void testA

    {
        Dummy.doDummyWork(arg1, arg2);//I m giving actual arguments
        //instead of moocking it calls the original method.
        Mockito.verify(printaskExecutor, times(1)).printSomething(anyString(), anyString());
    }
}

I have an autowired TaskExecutor in the class I m testing and I want to mock it.I have tried this in my code and It calls the actual method instead of do nothing and in the verify it errors out saying no interactions happened. How should I handle this situation?

user1364861
  • 301
  • 1
  • 2
  • 16

1 Answers1

0

I try to avoid using Mockito and Bean Containers together in one test. There are solutions for that problem. If you use Spring you should use @RunWith(SpringJUnit4Runner.class). More on this subject: Injecting Mockito mocks into a Spring bean

The clean way: Actually your class testDummy does not test Dummy but A. So you can rewrite your class in following way:

public class testA {
    @Mock
    PrintTaskExecutor printTaskExecutor;
    @InjectMocks
    A dummyA;

    ...

BTW: @Mock together with initMocks(this) and printaskExecutor = Mockito.mock(PrintTaskExecutor.class); do the same, you can skip the latter statement.

Community
  • 1
  • 1
CoronA
  • 7,717
  • 2
  • 26
  • 53
  • The problem here is my post construct doesn't work. If I dont use auto wired. – user1364861 May 28 '15 at 19:26
  • The `@PostConstruct` of `PrintTaskExecutor` will never be executed, because it is mocked. The `@PostConstruct` of `A` should be executed manually in the `@Before` section. – CoronA May 29 '15 at 05:13