宅男在线永久免费观看网直播,亚洲欧洲日产国码无码久久99,野花社区在线观看视频,亚洲人交乣女bbw,一本一本久久a久久精品综合不卡

全部
常見問題
產(chǎn)品動態(tài)
精選推薦

Spring Boot 2.x基礎(chǔ)教程:構(gòu)建RESTful API與單元測試

管理 管理 編輯 刪除

今天我們通過使用Spring MVC來實現(xiàn)一組對User對象操作的RESTful API,配合注釋詳細說明在Spring MVC中如何映射HTTP請求、如何傳參、如何編寫單元測試。

** RESTful API具體設(shè)計如下:**

b69b1202412160937429723.png

定義User實體

@Data
public class User {

    private Long id;
    private String name;
    private Integer age;

}

注意:相比1.x版本open in new window中自定義set和get函數(shù)的方式,這里使用@Data注解可以實現(xiàn)在編譯器自動添加set和get函數(shù)的效果。該注解是lombok提供的,只需要在pom中引入加入下面的依賴就可以支持:


    org.projectlombok
    lombok

實現(xiàn)對User對象的操作接口

@RestController
@RequestMapping(value = "/users")     // 通過這里配置使下面的映射都在/users下
public class UserController {

    // 創(chuàng)建線程安全的Map,模擬users信息的存儲
    static Map users = Collections.synchronizedMap(new HashMap());

    /**
     * 處理"/users/"的GET請求,用來獲取用戶列表
     *
     * @return
     */
    @GetMapping("/")
    public List getUserList() {
        // 還可以通過@RequestParam從頁面中傳遞參數(shù)來進行查詢條件或者翻頁信息的傳遞
        List r = new ArrayList(users.values());
        return r;
    }

    /**
     * 處理"/users/"的POST請求,用來創(chuàng)建User
     *
     * @param user
     * @return
     */
    @PostMapping("/")
    public String postUser(@RequestBody User user) {
        // @RequestBody注解用來綁定通過http請求中application/json類型上傳的數(shù)據(jù)
        users.put(user.getId(), user);
        return "success";
    }

    /**
     * 處理"/users/{id}"的GET請求,用來獲取url中id值的User信息
     *
     * @param id
     * @return
     */
    @GetMapping("/{id}")
    public User getUser(@PathVariable Long id) {
        // url中的id可通過@PathVariable綁定到函數(shù)的參數(shù)中
        return users.get(id);
    }

    /**
     * 處理"/users/{id}"的PUT請求,用來更新User信息
     *
     * @param id
     * @param user
     * @return
     */
    @PutMapping("/{id}")
    public String putUser(@PathVariable Long id, @RequestBody User user) {
        User u = users.get(id);
        u.setName(user.getName());
        u.setAge(user.getAge());
        users.put(id, u);
        return "success";
    }

    /**
     * 處理"/users/{id}"的DELETE請求,用來刪除User
     *
     * @param id
     * @return
     */
    @DeleteMapping("/{id}")
    public String deleteUser(@PathVariable Long id) {
        users.remove(id);
        return "success";
    }

}
這里相較1.x版本open in new window中,用更細化的@GetMapping、@PostMapping等系列注解替換了以前的@RequestMaping注解;另外,還使用@RequestBody替換了@ModelAttribute的參數(shù)綁定。

編寫單元測試

下面針對該Controller編寫測試用例驗證正確性,具體如下。當(dāng)然也可以通過瀏覽器插件等進行請求提交驗證。

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

    private MockMvc mvc;

    @Before
    public void setUp() {
        mvc = MockMvcBuilders.standaloneSetup(new UserController()).build();
    }

    @Test
    public void testUserController() throws Exception {
        // 測試UserController
        RequestBuilder request;

        // 1、get查一下user列表,應(yīng)該為空
        request = get("/users/");
        mvc.perform(request)
                .andExpect(status().isOk())
                .andExpect(content().string(equalTo("[]")));

        // 2、post提交一個user
        request = post("/users/")
                .contentType(MediaType.APPLICATION_JSON)
                .content("{\"id\":1,\"name\":\"測試大師\",\"age\":20}");
        mvc.perform(request)
                .andExpect(content().string(equalTo("success")));

        // 3、get獲取user列表,應(yīng)該有剛才插入的數(shù)據(jù)
        request = get("/users/");
        mvc.perform(request)
                .andExpect(status().isOk())
                .andExpect(content().string(equalTo("[{\"id\":1,\"name\":\"測試大師\",\"age\":20}]")));

        // 4、put修改id為1的user
        request = put("/users/1")
                .contentType(MediaType.APPLICATION_JSON)
                .content("{\"name\":\"測試終極大師\",\"age\":30}");
        mvc.perform(request)
                .andExpect(content().string(equalTo("success")));

        // 5、get一個id為1的user
        request = get("/users/1");
        mvc.perform(request)
                .andExpect(content().string(equalTo("{\"id\":1,\"name\":\"測試終極大師\",\"age\":30}")));

        // 6、del刪除id為1的user
        request = delete("/users/1");
        mvc.perform(request)
                .andExpect(content().string(equalTo("success")));

        // 7、get查一下user列表,應(yīng)該為空
        request = get("/users/");
        mvc.perform(request)
                .andExpect(status().isOk())
                .andExpect(content().string(equalTo("[]")));

    }

}

對MockMvc不熟悉的讀者,可能會碰到一些函數(shù)不存在而報錯。必須引入下面這些靜態(tài)函數(shù)的引用:

import static org.hamcrest.Matchers.equalTo;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.*;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
這里相較1.x版本open in new window中,主要有兩個地方不同。測試類采用@RunWith(SpringRunner.class)和@SpringBootTest修飾啟動;另外,由于POST和PUT接口的參數(shù)采用@RequestBody注解,所以提交的會是一個json字符串,而不是之前的參數(shù)形式,這里在定義請求的時候使用contentType(MediaType.APPLICATION_JSON)指定提交內(nèi)容為json格式,使用content傳入要提交的json字符串。如果用@ModelAttribute的話就得用param方法添加參數(shù),還是需要參考1.x版本的open in new window。

至此,我們通過引入web模塊(沒有做其他的任何配置),就可以輕松利用Spring MVC的功能,以非常簡潔的代碼完成了對User對象的RESTful API的創(chuàng)建以及單元測試的編寫。


注:本文轉(zhuǎn)載自“程序猿DD”,如有侵權(quán),請聯(lián)系刪除!

請登錄后查看

哈哈哈醬 最后編輯于2024-12-18 15:00:38

快捷回復(fù)
回復(fù)
回復(fù)
回復(fù)({{post_count}}) {{!is_user ? '我的回復(fù)' :'全部回復(fù)'}}
排序 默認正序 回復(fù)倒序 點贊倒序

{{item.user_info.nickname ? item.user_info.nickname : item.user_name}} LV.{{ item.user_info.bbs_level }}

作者 管理員 企業(yè)

{{item.floor}}# 同步到gitee 已同步到gitee {{item.is_suggest == 1? '取消推薦': '推薦'}}
{{item.is_suggest == 1? '取消推薦': '推薦'}}
沙發(fā) 板凳 地板 {{item.floor}}#
{{item.user_info.title || '暫無簡介'}}
附件

{{itemf.name}}

{{item.created_at}}  {{item.ip_address}}
打賞
已打賞¥{{item.reward_price}}
{{item.like_count}}
{{item.showReply ? '取消回復(fù)' : '回復(fù)'}}
刪除
回復(fù)
回復(fù)

{{itemc.user_info.nickname}}

{{itemc.user_name}}

回復(fù) {{itemc.comment_user_info.nickname}}

附件

{{itemf.name}}

{{itemc.created_at}}
打賞
已打賞¥{{itemc.reward_price}}
{{itemc.like_count}}
{{itemc.showReply ? '取消回復(fù)' : '回復(fù)'}}
刪除
回復(fù)
回復(fù)
查看更多
打賞
已打賞¥{{reward_price}}
965
{{like_count}}
{{collect_count}}
添加回復(fù) ({{post_count}})

相關(guān)推薦

快速安全登錄

使用微信掃碼登錄
{{item.label}} 加精
{{item.label}} {{item.label}} 板塊推薦 常見問題 產(chǎn)品動態(tài) 精選推薦 首頁頭條 首頁動態(tài) 首頁推薦
取 消 確 定
回復(fù)
回復(fù)
問題:
問題自動獲取的帖子內(nèi)容,不準確時需要手動修改. [獲取答案]
答案:
提交
bug 需求 取 消 確 定
打賞金額
當(dāng)前余額:¥{{rewardUserInfo.reward_price}}
{{item.price}}元
請輸入 0.1-{{reward_max_price}} 范圍內(nèi)的數(shù)值
打賞成功
¥{{price}}
完成 確認打賞

微信登錄/注冊

切換手機號登錄

{{ bind_phone ? '綁定手機' : '手機登錄'}}

{{codeText}}
切換微信登錄/注冊
暫不綁定
CRMEB客服

CRMEB咨詢熱線 咨詢熱線

400-8888-794

微信掃碼咨詢

CRMEB開源商城下載 源碼下載 CRMEB幫助文檔 幫助文檔
返回頂部 返回頂部
CRMEB客服