First, you have to add this dependency in your pom file to work with wire mock.
<dependency>
<groupId>com.github.tomakehurst</groupId>
<artifactId>wiremock-standalone</artifactId>
<version>2.19.0</version>
<scope>test</scope>
</dependency>
You need an initializer class to initialize the Class
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
@Configuration
@ComponentScan({"your package name*"})
public class AppInitializer{
}
In this initializer, you can set various configurations,
Then you have a base test class where you have the basic things which run in every test.
public abstract class AbstractTestBase {
/* Constant(s): */
private static final Logger LOGGER = LoggerFactory.getLogger(AbstractTestBase.class);
protected final static int HTTP_ENDPOINT_PORT = 8443;
protected final static String CLIENT_ID = "user";
protected final static String CLIENT_SECRET = "pass";
protected static final int DEFAULT_TIMEOUT = 5000;
protected WireMockServer mWireMockServer;
/**
* Performs preparations before each test.
*/
@BeforeEach
public void setup() {
mWireMockServer = new WireMockServer(HTTP_ENDPOINT_PORT);
mWireMockServer.start();
}
@AfterEach
public void tearDown() {
/* Stop the WireMock server. */
mWireMockServer.stop();
}
}
Then You may have the unit test classes for the wire mock
@ExtendWith(SpringExtension.class)
@ContextConfiguration(classes = {AppInitializer.class})
@ActiveProfiles("prod")
public class PhoneServiceUnitTest{
@Autowired
PhoneService phoneService;
@Test
public void callPhoneTest(){
mWireMockServer.stubFor(get(urlEqualTo("phone/call"))
.withHeader(HttpHeaders.ACCEPT,
equalTo(MediaType.APPLICATION_JSON_VALUE))
.willReturn(
aResponse()
.withStatus(200)
.withHeader(HttpHeaders.CONTENT_TYPE,
MediaType.APPLICATION_JSON_VALUE)
.withBodyFile("phone-response.json")
)
);
String result = phoneService.call("siva");
Assert.assertEquals(result,"Ok");
}
}
My phone-response.json json file
{
"data":"phone is called"
}
My PhoneService interface implementation
@Profile("dev")
Class PhoneServcieImp implements PhoneService{
private String owner = "siva";
public String call(String name){
if(name.equals(owner){
//It calls (phone/call)rest API and check the response if the response is 200 it will
//retrun "OK"
return "OK";
} else{
return "fail";}
}
}