簡體   English   中英

jUnit @beforeAll不起作用

[英]jUnit @beforeAll not working

我正在編寫REST API春季啟動的單元測試。

@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。錯誤顯示:

org.springframework.web.client.ResourceAccessException:“ http:// localhost:0 / api / v1 / actions ”的POST請求出現I / O錯誤

我的問題:有什么方法可以將@BeforeClasswebEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT一起使用,這意味着@LocalServerPort可以使用靜態值生成值嗎?

我想在測試運行前向Db添加1行。 但是,當我將@BeforeClass與靜態方法一起使用時,端口變量必須是靜態的,但不會生成值。 仍然為0。錯誤顯示:

因此,據我了解,您想寫下一個集成測試,該測試將從控制器流向DB。 這是我的建議。

@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);
    }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM