Search code examples
javatestingoracle-sqldeveloperjunit4

Delay in DB access with JUnit4?


I am working on a Java console app that requires JUnit version 4. I'd like to have a single test that checks if the boolean field in a User object is successfully updated from 0 to 1 and then back again.

    public void approveTest() throws BankException {
        // get the test user to work on
        User user = udi.accessUserObject("UNITtestApprove");

        // find their user id (it is 590)
        String user_id = user.getUser_id();

        //approve the account, test that the boolean/number set to 1
        udi.approve(user_id);
        assert(user.getApproved() == 1);

        //remove approval, test that the boolean/number reset to 0
        udi.removeApproval(user_id);
        assert(user.getApproved() == 0);

    }

This test fails. If I split it into two tests, one passes while the other fails, and then the reverse. It seems that my getters aren't fetching the new, updated value from my db, but after the tests are finished that value is definitely updated. I am positive that both methods work when I use them in my app by accessing my DAO layer.

I'm using Spring, Oracle SQL Developer, and a AWS database. Can anyone help me spot the problem, whether it is an order issue or some sort of timing issue?


Solution

  • You're performing udi.approve(user_id), but you're not fetching the latest version from the database prior to checking its value. Instead you're asserting on the User object you obtained before the update. I think you need something more like:

      public void approveTest() throws BankException {
            // get the test user to work on
            final String userName = "UNITtestApprove";
            final User user = getUserByName(userName);
    
            // find their user id (it is 590)
            String userId = user.getUser_id();
    
            // approve the account, test that the boolean/number set to 1
            udi.approve(userId);
            assertEquals(1, getUserByName(userName).getApproved());
    
            // remove approval, test that the boolean/number reset to 0
            udi.removeApproval(userId);
            assertEquals(0, getUserByName(userName).getApproved());
    
        }
    
        public User getUserByName(final String userName) {
            return udi.accessUserObject(userName);
        }