Writing a JUnit test case for a constructor

cellifake :

I have an assignment for school that involves learning how to use JUnit4. I need to make sure this constructor works properly, however, I am unsure of how to do so. There is a getter for the balance, so testing whether or not the constructor works with this is pretty easy, however, I don't know how to write a test case that involves user and pass as these do not have getters. Do I write a case for each individual parameter? Writing cases for methods that return a value hasn't been too difficult but I am clueless in terms of writing one for this constructor. Thanks!

public class BankAccount {

    // Starting balance
    private float balance = 0.0f;
    // Username and password
    private char[] username = null;
    private char[] password = null;


    public BankAccount(float balance, char[] user,char[] pass) {
        this.balance = balance;
        this.username = user;
        this.password = pass;
    }
}
i.bondarenko :

In this case you should write one test. You do not need write any more because it will be just duplicates. This test should control fields assignment:

@Test
public void propertiesAreSetOnBankAccountConstructor() {
    float balance = 100F;
    char[] userNameArray = {'u'};
    char[] passArray = {'p'};
    BankAccount testedObject = new BankAccount(balance, userNameArray, passArray);

    assertEquals(balance, testedObject.getBalance(), 0F);
    assertSame(userNameArray, testedObject.getUsername());
    assertSame(passArray, testedObject.getPassword());
}

Update: If there are no getters you could use org.springframework.test.util.ReflectionTestUtils (or just pure reflections):

@Test
public void propertiesAreSetOnBankAccountConstructor() {
    float balance = 100F;
    char[] userNameArray = {'u'};
    char[] passArray = {'p'};
    BankAccount testedObject = new BankAccount(balance, userNameArray, passArray);

    assertEquals(balance, ((Float)ReflectionTestUtils.getField(testedObject, "balance")), 0F);
    assertSame(userNameArray, ReflectionTestUtils.getField(testedObject, "username"));
    assertSame(passArray, ReflectionTestUtils.getField(testedObject, "password"));
}

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=165205&siteId=1