I have a requirement to test a SpringBoot application where I run the tests against the end point (for now, locally).
There is one call from a service to external service (s3
), and I just need to mock this, so that we don't do a live call to s3
from our test.
I use Mockito for mocking.
The call stack:
Controller -service
-external service.
From my test, I just hit the end point url (localhost:8080/actions/domyjob
)
This is my controller:
@RestController
@RequestMapping("/myjob")
public class MyController{
@Autowired
private MyService myService;
@RequestMapping(path = "/doJobInMyService", method = POST)
public void doJobInMyService(){
myService.doMyJob()
}
}
This is my service:
@Service
public class MyService {
@Autowired
private s3Client AmazonS3Client;
doMyJob() {
s3Client.putObject(new PutObjectRequest());
}
}
If you see, if I want to test the entire flow, by calling localhost:8080/myjob/doJobInMyService
and just mock s3Client.putObject(new PutObjectRequest())
, so that external calls to s3
is not done.
Tried this, but I had still no luck:
@ActiveProfiles("MyTestConfig")
@RunWith(SpringJUnit4ClassRunner.class)
public class MyTest extends BaseTest {
@Autowired
private AmazonS3Client amazonS3Client;
@Test
public void testMyResponse() {
try {
Mockito.when(amazonS3Client.putObject(anyObject())).thenReturn(new PutObjectResult());
assertNotNull(getMyClient().doMyJob());
} catch(Exception e) {
}
}
}
@Profile("MyTestConfig")
@Configuration
public class MyTestConfiguration {
@Bean
@Primary
public AmazonS3Client amazonS3Client() {
return Mockito.mock(AmazonS3Client.class);
}