我使用resttemplate来测试我的Web服务,但是当我运行测试时,我与应用程序有错误连接

时间:2019-05-14 09:10:13

标签: spring resttemplate

我知道我使用h2作为数据库,所以我使用resttemplate来测试我的Web服务,但是当我运行测试时,我遇到了应用程序连接错误 错误: org.springframework.we.client.RessourceAccessException:获取“ http://localhost:8082 / parcours”请求时发生I / O错误:连接到本地主机:8082 我不知道如何自动启动spring boot,它指向我的应用程序文件,该文件指向h2数据库而不是其他数据库

@Configuration
public class TestConfig
{
    @Bean
public TestRestTemplate myRestTemplate()
{
return new TestRestTemplate();
}

}



@RunWith(SpringRunner.class)
@ContextConfiguration(location ={"file:src/ressources/applicationContext.xml"},classes = TestConfig.class)
@RestClienTest(value={ParcoursRessource.class})
@SpringBootTest(classes = Application.class)
public class TestParcoursRessource 
{

@Autowired
    private RestTemplate myRestTemplate;

@Test
public void listerParcours()
{
 ResponseEntity<String> responseEntity = myRestTemplate.getForEntity("http://localhost:8082/parcours",String.class);
Assert.assertEquals(OK.getStatusCode(),responseEntity.getStatusCodeValue())
}
}

2 个答案:

答案 0 :(得分:0)

我建议您尝试使用RestAssured。

DOC:https://github.com/rest-assured/rest-assured/wiki/GettingStarted

示例配置

抽象类EndpointTest。指向您的应用数据库配置文件的ContextConfiguration。这将在测试包的application.yml中查找您的数据源属性,因此您可以将h2仅用于测试:

@RunWith(SpringRunner.class)
@ContextConfiguration(classes = {YourAppConfig.class})
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
public abstract class EndpointTest {

    // App port
    @Value("${local.server.port}") int port;

    @Before
    public void setUp() {
        RestAssured.port = port;
    }
}

示例测试方法:

public class ExampleEndpointTest extends EndpointTest {
    @Test
    public void deleteMultiple(){

        given()
             .pathParam("id","a")
        .when()
             .delete("/example/query/{id}")
        .then()
             .statusCode(HttpStatus.SC_NO_CONTENT);
    }
}

答案 1 :(得分:0)

这里是使用嘲笑mvcm进行获取和发布服务的示例,嘲笑mvcmvc可与spring starter测试依赖项本身一起使用

import static org.junit.Assert.fail;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.delete;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;

import java.time.LocalDateTime;
import java.util.List;

import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.test.context.SpringBootTest.WebEnvironment;
import org.springframework.boot.web.server.LocalServerPort;
import org.springframework.http.MediaType;
import org.springframework.security.test.context.support.WithMockUser;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.context.WebApplicationContext;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.ObjectWriter;
import com.fasterxml.jackson.databind.SerializationFeature;




@RunWith(SpringRunner.class)
@SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT)
public class AppTest {


    @LocalServerPort
    int randomServerPort;


    @Autowired
    private WebApplicationContext context;




    private MockMvc mvc;


    @Before
    public void setup() {
        mvc = MockMvcBuilders
          .webAppContextSetup(context)
         // .apply(springSecurity())
          .build();
    }



    @Test
    @WithMockUser("spring")
    public void testGetPage() throws Exception {
        mvc.perform(get(<url>).contentType(MediaType.APPLICATION_JSON))
           .andExpect(status().is(200));
    }



    @Test
    @WithMockUser("spring")
    public void testRolePost() throws Exception {
        Role role = new Role();

        role.setRoleName("Test Role");
        role.setRead(true);
        role.setWrite(false);
         ObjectMapper mapper = new ObjectMapper();
            mapper.configure(SerializationFeature.WRAP_ROOT_VALUE, false);
            ObjectWriter ow = mapper.writer().withDefaultPrettyPrinter();
            String requestJson=ow.writeValueAsString(role );
        mvc.perform(post("/addrole").contentType(MediaType.APPLICATION_JSON) .content(requestJson))
           .andExpect(status().is(200));

    }

}