0

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:

test.htmSpring Boot - Rest Controller Unit Test

Sun
  • 3,444
  • 7
  • 53
  • 83
  • My first guess would be that the test itself must be annotated as Spring test, not its base class – knittl Feb 01 '22 at 07:02
  • 1
    Your test is wrong. Autowire `MockMvc` and ditch your `setUp` method. That is actually interfering with the Spring Boot setup. Finally when using `@SpringBootTest` it will run with a mocked servlet environment which doesn't have a port, if you want to really start it on a port you need to change from MOCK to DEFINED_PORT. – M. Deinum Feb 01 '22 at 07:04

0 Answers0