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?
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();
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With