mercredi 26 avril 2017

Unit Test a private field which is behavior relevant

first of all: I found few solutions for my problem but the "newest" one was from 2014 and used reflections so I hope I could maybe find some more advanced solutions for my question.

Thats the case and its about migrateUser and canAdd. This is an example class to make my question easily visible.

public class UserInterfaceImpl implements UserInterface {

    private final List<T> accountList = new LinkedList<>();
    private final AccountInterface accountInterface;
    private boolean bonusReceived = false;

    public UserInterfaceImpl(AccountInterface accountInterface) {
        this.accountInterface = accountInterface;
    }

    public void migrateUser(AccountMergerInterface accountMerger, UserInterface oldUser) {
        boolean success = accountMerger.performChange(this, oldUser);
        if (success && !bonusReceived) {
            //addBonus
            accountInterface.deposit(1);
            bonusReceived = false;
        }
    }

    public boolean canAdd() {
        return accountList > 0;
    }

    public AccountInterface getAccount() {
        return accountInterface;
    }
}

The migrateUser class changes the some account Data which is not relevant for my test because I would test it seperatly of course (should be like that what I read so far).

So I wonder, how can I see if the behavior of that class changes the bonusReceived correctly? Without using reflections and do it as sophisticated as possible?

My first attempt was that:

@Test
public void testMigrateUser() {
    AccountMergerInterface test = mock(AccountMergerInterface.class);

    // define return value for method getUniqueId()
    when(test.performChange()).thenReturn(true);
}

But know I cannot continue. The rule should be in my example to have no getter and setter! The class should be like my example.

I don't know how to:

  1. set bonusReceived to false before migrateUser is executed that accountInterface.deposit(1); is not executed
  2. see if bonusReceived will be set to false if the if() continue is true
  3. Same questions for the List. How can I access the private field of List, add an Object so that the return value is true and false. Or should I "simulate" a List and if yes, how can I do that?

Thanks in advance!

Aucun commentaire:

Enregistrer un commentaire