My application is running in local, I am trying to do Spring Rest Controller testing.
It is running in 8089 port.
In application.yml
spring:
profiles:
active: sit
In application-sit.yml
server:
port: 8089
servlet:
context-path: /myapp
In My base test case:
@RunWith(SpringJUnit4ClassRunner.class)
@SpringBootTest(classes = MyApplication.class)
@WebAppConfiguration
public abstract class AbstractTest {
protected MockMvc mvc;
@Autowired
WebApplicationContext webApplicationContext;
@Value("${server.port}")
int serverPort;
/* @LocalManagementPort
int randomManagementPort;*/
protected void setUp() {
mvc = MockMvcBuilders.webAppContextSetup(webApplicationContext).build();
}
protected String mapToJson(Object obj) throws JsonProcessingException {
ObjectMapper objectMapper = new ObjectMapper();
return objectMapper.writeValueAsString(obj);
}
protected <T> T mapFromJson(String json, Class<T> clazz)
throws JsonParseException, JsonMappingException, IOException {
ObjectMapper objectMapper = new ObjectMapper();
return objectMapper.readValue(json, clazz);
}
}
My Controller Test class:
public class OtpControllerTest extends AbstractTest {
@Override
@Before
public void setUp() {
super.setUp();
}
@Test
public void sendOtpTest() throws Exception {
String uri = "/sendOtp";
SendOTPRequestDTO otpRequest = new SendOTPRequestDTO();
otpRequest.setClientId("default2");
otpRequest.setTag("tag");
otpRequest.setMobileNumber("4444888888");
String inputJson = super.mapToJson(otpRequest);
MvcResult mvcResult = mvc.perform(MockMvcRequestBuilders.post(uri)
//.accept(MediaType.APPLICATION_JSON_VALUE)).andReturn()
.contentType(MediaType.APPLICATION_JSON_VALUE)
.content(inputJson)).andReturn();
int status = mvcResult.getResponse().getStatus();
String content = mvcResult.getResponse().getContentAsString();
assertEquals(8089,serverPort);
assertEquals(200, status);
}
}
I am getting output like this:
java.lang.AssertionError: expected:<8089> but was:<-1>
I gone through the all similar issues and tried even no result.
I am fallowing this source: