如何在单位测试中模拟功能Actix Web
我有一个具有2层的API服务:API和存储库。 API层是请求处理和业务逻辑定义的地方,而存储库是数据库调用功能。我想在我的API层的单元测试上模拟数据库调用功能,有什么办法可以使用Actix Web?
pub fn login(db: web::Data<Pool>, payload: Json<LoginInput>) -> Result<Token, Error> {
// Function i want to mock:
let user =
match get_user_by_email(&db.get().unwrap(), payload.email.to_string()) {
// This return status code of bad request
Err(e) => return Error::InvalidUser,
Ok(user) => user,
};
let user_claims = UserClaims {
id: user.id,
email: user.email
};
match verify(payload.password.to_string(), &user.password) {
Err(e) => return Error::BadRequest(e),
Ok(result) => match result {
false => return Error::InvalidUser,
_ => {}
},
};
let token = generate_access_and_refresh_token(user_claims);
token
}
测试:
#[actix_web::test]
async fn test_login() {
let payload = create_mock_login_payload();
let req = test::TestRequest::default()
.set_json(payload)
.to_http_request();
let resp = login(req).await.unwrap();
assert_eq!(resp.status(), StatusCode::BadRequest);
}
我想要的模拟功能行为:
fn get_user_by_email(db: Pool, email: String) -> Result<User, Error> {
if !email_valid(email) {
return Err(Error::InvalidEmail);
}
Ok(create_mock_user())
}
I have an api service that has 2 layer: api and repository. The api layer is where the request handling and business logic defined, while repository is a database call functions. I want to mock the database call function on the unit testing of my api layer, is there any way i can do it with actix web?
pub fn login(db: web::Data<Pool>, payload: Json<LoginInput>) -> Result<Token, Error> {
// Function i want to mock:
let user =
match get_user_by_email(&db.get().unwrap(), payload.email.to_string()) {
// This return status code of bad request
Err(e) => return Error::InvalidUser,
Ok(user) => user,
};
let user_claims = UserClaims {
id: user.id,
email: user.email
};
match verify(payload.password.to_string(), &user.password) {
Err(e) => return Error::BadRequest(e),
Ok(result) => match result {
false => return Error::InvalidUser,
_ => {}
},
};
let token = generate_access_and_refresh_token(user_claims);
token
}
The test:
#[actix_web::test]
async fn test_login() {
let payload = create_mock_login_payload();
let req = test::TestRequest::default()
.set_json(payload)
.to_http_request();
let resp = login(req).await.unwrap();
assert_eq!(resp.status(), StatusCode::BadRequest);
}
The mock function behavior that i want:
fn get_user_by_email(db: Pool, email: String) -> Result<User, Error> {
if !email_valid(email) {
return Err(Error::InvalidEmail);
}
Ok(create_mock_user())
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论