How to mock a struct fields while unit testing?

Hi All,

I am trying to write a test case for a function which takes in a hashmap of user structs. Inside that function, I am only using one field of the user struct. I don't have a new() or default() implemented since it is not required and I use this struct as a group of fields.

For example,

pub struct User {
    username: String,
    shortusername: String,
    longusername: String,
    address1: String,
    address2: String,
    address3: String,
    address4: String,
    contact: i32,
    active: bool
}

//Pseudo code which counts the number of items having active as true
fn count_active_users(users: HashMap<String, User>) -> usize { 
    // do something with active field 
}

Now in my testcase, I wanted to initialise only the active field. So my test case is something like below,

#[test]
fn test_count_active_users() {
    let users = HashMap::new();
    let user1 = User {active: true};
    let user2 = User {active: false};
    let user3 = User {active: true};
    users.insert("user1".tostring(), user1);
    users.insert("user2".tostring(), user2);
    users.insert("user3".tostring(), user3);
    assert_eq!(count_active_users(users), 2);
}

However, as we know, it throws compile error since the other fields are not initialised. Is it possible to set only certain field using any mock crate? Is it possible to do this with mockall?

If you derive Default, you can do this:

#[derive(Default)]
pub struct User {
    username: String,
    shortusername: String,
    longusername: String,
    address1: String,
    address2: String,
    address3: String,
    address4: String,
    contact: i32,
    active: bool
}

#[test]
fn test_count_active_users() {
    let users = HashMap::new();
    let user1 = User { active: true, ..Default::default() };
    let user2 = User { active: false, ..Default::default() };
    let user3 = User { active: true, ..Default::default() };
    users.insert("user1".to_string(), user1);
    users.insert("user2".to_string(), user2);
    users.insert("user3".to_string(), user3);
    assert_eq!(count_active_users(users), 2);
}
1 Like

Thanks @alice. It worked!