【问题标题】:fail to update a property in multi-threaded code无法在多线程代码中更新属性
【发布时间】:2015-08-04 15:31:41
【问题描述】:

我尝试编写这个单元测试

@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"));
}

但是我的测试失败了。

用户名没有改变。 你会添加“睡眠”吗?还有什么?

【问题讨论】:

    标签: java multithreading unit-testing thread-safety


    【解决方案1】:

    可能考虑使用不同的测试方法。您似乎正在尝试测试您的 usersServerAccess 类 - 专注于该类的单个单元测试(可能使用模拟框架,例如 Mockito)。通过此单元测试,您可以确保该类中的代码按预期工作。

    您在此处尝试执行的操作看起来像是多线程集成测试,在最好的情况下这很棘手(@see Unit testing a multithreaded application?)。此代码如何适合您的应用程序框架?也许考虑一个端到端的测试框架,比如JBehaveCucumber

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-03-28
      • 1970-01-01
      • 2021-11-08
      • 2019-07-06
      • 2017-12-06
      • 1970-01-01
      相关资源
      最近更新 更多