springboot对controller服务测试的代码示例

其中AdminApplicationTest 为测试的AdminApplication

@RunWith(SpringRunner.class)
@SpringBootTest
public class AdminApplicationTest {


}

import io.renren.AdminApplicationTest;
import io.renren.modules.tool.dto.BlogArticleDto;
import org.junit.Before;
import org.junit.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.MvcResult;
import org.springframework.test.web.servlet.request.MockMvcRequestBuilders;
import org.springframework.test.web.servlet.result.MockMvcResultHandlers;
import org.springframework.test.web.servlet.result.MockMvcResultMatchers;
import org.springframework.test.web.servlet.setup.MockMvcBuilders;

/**
 * @author No One
 * @description:
 * @date 2022/6/29 10:33
 */
public class NoteArticleControllerTest extends AdminApplicationTest {

    @Autowired
    private NoteArticleController noteArticleController;

    private MockMvc mockMvc;

    @Before
    public void setUp() throws Exception {
        mockMvc = MockMvcBuilders.standaloneSetup(noteArticleController).build();
    }

    @Test
    public void page() throws Exception {
        BlogArticleDto blogArticleDto = new BlogArticleDto();
        MvcResult mvcResult = mockMvc.perform(MockMvcRequestBuilders.get("/note/note/page")
//                .contentType(MediaType.APPLICATION_JSON_VALUE)
//                .content(JSONUtil.toJsonStr(blogArticleDto))
        )
                .andExpect(MockMvcResultMatchers.status().isOk())
                .andDo(MockMvcResultHandlers.print())
                .andReturn();
        System.out.println(mvcResult.getResponse().getContentAsString());
    }

}

你可能感兴趣的:(spring,boot,后端,java)