0

I try to write this unit-test

@Test
public void setUserNamePropertyFromMultiThreadsUpdatesCorrectly() throws Exception {
    boolean oldVal = UsersConfig.s.NO_DB_MODE;
        final List<String> lastName = new ArrayList<String>();
        UsersConfig.s.NO_DB_MODE = true;

        String user1 = testUtils.generateUserName();
        final Long createdId = testUtils.createUserWithProperties(ImmutableMap.of("username", user1, "A", "A1",
                "isStaff", "true"));

        List<Callable<Void>> callables = new ArrayList<Callable<Void>>();
        for (int i = 0; i < 20; i++) {
            callables.add(new Callable<Void>() {
                @Override
                public Void call() throws Exception {
                    String user2 = testUtils.generateUserName();
                    boolean isSuccess = usersServerAccess.setProperties(createdId,
                            ImmutableMap.of("isStaff", "dont_know", "username", user2),
                            1, "test set", someTimeOut);
                    assertTrue(isSuccess);

                    synchronized (lastName) {
                        lastName.add(user2);
                    }
                    return null;
                }
            });

        ExecutorService executorService = Executors.newFixedThreadPool(10);
        try {
            executorService.invokeAll(callables);
            executorService.shutdown();
            executorService.awaitTermination(1, TimeUnit.MINUTES);
        } catch (InterruptedException e) {
            e.printStackTrace();
            throw new RuntimeException(e);
        }

        User returnedUser = usersServerAccess.getUser(createdId, "get test", someTimeOut);
        assertThat(returnedUser.getProperty("username"), equalTo(lastName.get(0)));
        assertThat(returnedUser.getProperty("A"), equalTo("A1"));
        assertThat(returnedUser.getProperty("isStaff"), equalTo("dont_know"));
}

however my test fails.

The username is not changed. would you add "sleep" ? something else?

Elad Benda
  • 35,076
  • 87
  • 265
  • 471

1 Answers1

0

Possibly consider a different testing approach. It appears that you are trying to test your usersServerAccess class - focus on an individual unit test for this class (possibly using a mocking framework such as Mockito). With this unit test, you can be sure that your code in that class is working as expected.

What you're trying to do here looks like a multithreaded integration test, which is tricky at the best of times (@see Unit testing a multithreaded application?). How does this code fit into the framework of your application? Maybe consider an end to end testing framework like JBehave or Cucumber.

Community
  • 1
  • 1
Kieran
  • 343
  • 2
  • 10