Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using Mockito annotations with spring

I am using spring in my application and I want to write unit tests for all my classes. I call few external webservices from my application and i want to mock them using Mockito since I just want to test my functionality.

Lets say I have the following scenario

This is my webservice interface

public interface MyWebService {
    public String getSomeData(int id);
}

I use the above service this way

public interface MyService {
    int doSomethingElse(String str);
}

public class MyServiceImpl implements MyService {

    private MyWebService myWebService;

    int doSomethingElse(String str) {
        .....
        myWebService.getSomeData(id);
        ...
    }
}

public interface MyService1 {
    Stirng methodToBeTested();
}


public class Class1 implements MyService1{
    @Resource
    private MyService myService;

    public Stirng methodToBeTested() {
        myService.doSomethingElse("..");
    }
}

I wrote the uint test case as below. I am spying MyService here so as to run the unit test.

public class class1Test {

    @Spy
    MyService myService;

    @Resource
    @InjectMocks
    Class1 class1;

    public void setUPTest() {
        MockitoAnnotations.initMocks(this);
    Mockito.doReturn(123).when(myService).doSomethingElse("someString");
    }

    @Test
    public void methodToBeTestedTest() {
        this.setUPTest();
            ...
            class1.methodToBeTested();
    }

}

When I run the test, what I see is that, I get the value from the webservice insted of what i mention while stubbing.

Can anyone help me with this?

like image 723
rahul Avatar asked Mar 26 '13 11:03

rahul


1 Answers

I solved this by using spring java config. I extended my default config file in my test config file.

    @Configuration
    public class TestConfig extends DefaultConfig {

      @Bean
      public MyService myService() {
        return Mockito.spy(new MyServiceImpl());
      }
    }

Now my test class goes like this

public class class1Test {

    @Resource
    MyService myService;

    @Resource
    Class1 class1;

    public void setUPTest() {
        MockitoAnnotations.initMocks(this);
    Mockito.doReturn(123).when(myService).doSomethingElse("someString");
    }

    @Test
    public void methodToBeTestedTest() {
        this.setUPTest();
            ...
            class1.methodToBeTested();
    }

}
like image 87
rahul Avatar answered Sep 26 '22 02:09

rahul