Writing a JUnit test case for a constructor

cel*_*ake 2 java junit4

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;
    }
}
Run Code Online (Sandbox Code Playgroud)

i.b*_*nko 5

在这种情况下,您应该编写一个测试。您无需再写,因为它只是重复的。该测试应控制字段分配:

@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());
}
Run Code Online (Sandbox Code Playgroud)

更新:如果没有吸气剂,您可以使用org.springframework.test.util.ReflectionTestUtils(或仅使用纯反射):

@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"));
}
Run Code Online (Sandbox Code Playgroud)