jUnit @beforeAll不起作用 [英] jUnit @beforeAll not working

查看:1236
本文介绍了jUnit @beforeAll不起作用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在为rest api弹簧靴编写单元测试.

I'm writing unit test for rest api spring boot.

@RunWith(SpringRunner.class)
@SpringBootTest(classes = WorkflowEngineApiApplication.class, webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
public class ActionControllerTest {
    @LocalServerPort
    public int port;

    private final TestRestTemplate testRestTemplate = new TestRestTemplate();

    private final HttpHeaders headers = new HttpHeaders();

    private long actionId;

    @BeforeClass
    public static void init() throws Exception{
        String url="/api/v1/actions";
        JSONObject action = new JSONObject();
        action.put("name", "Name Test");
        action.put("actionTypeId", 4L);
        action.put("description", null);
        action.put("createdBy", 2L);
        action.put("processId", 2L);
        headers.setContentType(MediaType.APPLICATION_JSON_UTF8);
        ResponseEntity<ApiResponse> response = getResponse(url, HttpMethod.POST, action.toString());
    }

    private static ResponseEntity<ApiResponse> getResponse(String url, HttpMethod method, Object action){
        HttpEntity<Object> entity = new HttpEntity<>(action, headers);
        return testRestTemplate.exchange(createURL(url), method, entity, ApiResponse.class);
    }

    /**
     * create url http://localhost:...
     * @param uri String
     * @return String
     */
    public static String createURL(String uri) {
        return "http://localhost:" + port + uri;
    }
}

我想在测试运行前向Db添加1行.但是,当我将@BeforeClass与静态方法一起使用时,端口变量必须是静态的,但不会生成值.仍然是0. 错误显示:

I want to add 1 row to Db before test run. But when I use @BeforeClass with static method, port variable must be static, but it not generate value. It's still 0. Error show:

org.springframework.web.client.ResourceAccessException:I/O错误发生在 POST请求" http://localhost:0/api/v1/actions "

org.springframework.web.client.ResourceAccessException: I/O error on POST request for "http://localhost:0/api/v1/actions"

我的问题:是否可以将@BeforeClasswebEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT一起使用,这意味着@LocalServerPort可以通过静态方式生成值?

My question: Is there any way to use @BeforeClass with webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT, it's mean @LocalServerPort generate value with static ?

推荐答案

我想在测试运行前向Db添加1行.但是,当我将@BeforeClass与静态方法一起使用时,端口变量必须是静态的,但不会生成值.仍然是0.错误显示:

I want to add 1 row to Db before test run. But when I use @BeforeClass with static method, port variable must be static, but it not generate value. It's still 0. Error show:

所以,我的理解是,您想写下一个集成测试,该测试将控制器从控制器流到数据库.这是我的建议.

So, what I understood is that, you want to write down integration test which flows form controller to DB. Here is my suggestion.

@RunWith(SpringRunner.class)
@SpringBootTest
@WebAppConfiguration
@Transactional    
public class MyIntTest {

    private MockMvc mockMvc;

    @Autowired
    private WebApplicationContext ctx;  

    @Before
    public void setUp() {
        this.mockMvc = MockMvcBuilders.webAppContextSetup(ctx).build();

        MockHttpServletRequestBuilder builder = MockMvcRequestBuilders.post(**Your URL").accept(MediaType.APPLICATION_JSON)
                .contentType(MediaType.APPLICATION_JSON);

        builder.setContent("Your JSON request data");

        // This will invoke POST request to "URL"
        this.mockMvc.perform(builder);

        // If you want to verify your result
       MvcResult result = this.mockMvc.perform(builder).andReturn();

      // Read response. If its custom class then just change return type.
      List responses = getPojoFromMvcResult(result, List.class);
    }

    public static <T> T getPojoFromMvcResult(MvcResult result, Class<T> valueType) throws IOException {
        try {
            MockHttpServletResponse response = result.getResponse();
            String responseJson = response.getContentAsString();
            return convertJsonToObject(responseJson, valueType);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    public static <T> T convertJsonToObject(String content, Class<T> valueType) throws IOException {
        return new ObjectMapper().readValue(content, valueType);
    }
}

这篇关于jUnit @beforeAll不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆