新足迹

 找回密码
 注册

精华好帖回顾

· 菜鸟小厨做的几个小菜(6月26日更新,在PAGE 5) (2005-4-4) maribel · 搜集整理煮妇(夫)采购,储存,食物保鲜的心得秘绝------跟贴加分。谢绝灌水。 (2008-8-20) Tiger_Karen
· 【美食接龙】第2棒 ~ 彩椒鱿鱼丝 - 接棒食材 - 鱿鱼 - E&E(福美丽)请接棒啦~ (2009-5-27) tinanakoo · 美食美刻---我家的重口味第二波!毛血旺,火爆肥肠,香辣猪蹄,兔肉香锅,手撕茄子 (2014-1-6) ta_xiang
Advertisement
Advertisement
查看: 1334|回复: 2

[IT] 如何unit test这段rust 代码? [复制链接]

发表于 2021-8-1 06:46 |显示全部楼层
此文章由 DDD888 原创或转贴,不代表本站立场和观点,版权归 oursteps.com.au 和作者 DDD888 所有!转贴必须注明作者、出处和本声明,并保持内容完整
use actix_web::body::{Body, ResponseBody};

pub trait BodyTest {
    fn as_str(&self) -> &str;
}

impl BodyTest for ResponseBody<Body> {
    fn as_str(&self) -> &str {
        match self {
            ResponseBody::Body(ref b) => match b {
                Body::Bytes(ref by) => std::str::from_utf8(&by).unwrap(),
                _ => panic!(),
            },
            ResponseBody::Other(ref b) => match b {
                Body::Bytes(ref by) => std::str::from_utf8(&by).unwrap(),
                _ => panic!(),
            },
        }
    }
}

谢谢
Advertisement
Advertisement

发表于 2021-8-2 12:41 |显示全部楼层
此文章由 DDD888 原创或转贴,不代表本站立场和观点,版权归 oursteps.com.au 和作者 DDD888 所有!转贴必须注明作者、出处和本声明,并保持内容完整
本帖最后由 DDD888 于 2021-8-2 14:01 编辑

我自己来回答自己的问题

use actix_web::body::{Body, ResponseBody};

pub trait BodyTest {
    fn as_str(&self) -> &str;
}

impl BodyTest for ResponseBody<Body> {
    fn as_str(&self) -> &str {
        match self {
            ResponseBody::Body(ref b) => match b {
                Body::Bytes(ref by) => std::str::from_utf8(&by).unwrap(),
                _ => panic!(),
            },
            ResponseBody::Other(ref b) => match b {
                Body::Bytes(ref by) => std::str::from_utf8(&by).unwrap(),
                _ => panic!(),
            },
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use actix_web::body::Body;

    #[test]
    fn body_empty_expect_empty() {
        let response_body_empty = ResponseBody::Body(Body::from(""));
        assert_eq!(response_body_empty.as_str(), "");
    }

    #[test]
    fn body_not_empty_expect_hello() {
        let response_body = ResponseBody::Body(Body::from("hello"));
        assert_eq!(response_body.as_str(), "hello");
    }

    #[test]
    fn body_other_empty_expect_empty() {
        let response_body = ResponseBody::Other(Body::from(""));
        assert_eq!(response_body.as_str(), "");
    }

    #[test]
    fn body_other_not_empty_expect_hello() {
        let response_body = ResponseBody::Other(Body::from("hello"));
        assert_eq!(response_body.as_str(), "hello");
    }
}

发表于 2021-8-2 13:15 |显示全部楼层
此文章由 git 原创或转贴,不代表本站立场和观点,版权归 oursteps.com.au 和作者 git 所有!转贴必须注明作者、出处和本声明,并保持内容完整
Rust语言比较小众,要是Java, C++, C#估计很多人都能答

发表回复

您需要登录后才可以回帖 登录 | 注册

本版积分规则

Advertisement
Advertisement
返回顶部