'How to mock function on unit test actix web
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())
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|