【问题标题】:Calling methods from jUnit test从 jUnit 测试调用方法
【发布时间】:2013-09-05 19:49:28
【问题描述】:

下面是我的 jUnit 测试,我试图在我的 OSGiFramework 类中调用 afterPropertiesSet。但不知何故,getBundlesInformation 方法在该流程中没有被调用。

当我调试我的 jUnit 测试时,afterPropertiesSet 方法被调用,然后它转到 initializeModelFramework 方法,然后它永远不会转到 getBundlesInformation 方法。

@Test
public void testOSGiFramework() {

    Method method;
    try {
        method = OSGiFramework.class.getDeclaredMethod("afterPropertiesSet", null);
        Object o = method.invoke(new OSGiFramework(), null);

        Assert.assertEquals(false, o instanceof Void);
    }
}

以下是OSGiFramework类中的方法-

private final ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(1);

@Override
public void afterPropertiesSet() throws Exception {

    try {
        initializeModelFramework();
    }
}

private void initializeModelFramework() {

    final ScheduledFuture<?> taskHandle = scheduler.scheduleAtFixedRate(
            new Runnable() {
                public void run() {
                    try {
                        getBundlesInformation();
                    }catch(Exception ex) {
                        LOG.log(Level.SEVERE, "Exception in OSGiFramework::initializeModelFramework " +ex);
                        ex.printStackTrace();
                    }
                }
            }, 0, 30, TimeUnit.MINUTES);
}

protected static void getBundlesInformation() throws BundleException, Exception {
    System.out.println("Hello");
}

有谁知道可能是什么问题?

【问题讨论】:

    标签: java junit


    【解决方案1】:

    getBundlesInformation() 方法在不同的线程上运行,那么谁能说它没有在 assert 方法或测试之后运行呢?无论哪种方式,问题似乎都与尝试 Junit 测试线程应用程序有关。

    您可能想研究使用不同线程的 Junit 测试。我个人从来没有这样做过,但是在快速的谷歌搜索之后,它似乎不是一个非常简单的任务,并且可能更容易避免它/分解测试,所以他们不必处理不同的线程。

    对不起,如果这个答案没有更多用处 - 如果有经验的人看到这个,请尝试给出更好的答案!

    一些快速搜索将我带到:

    Unit testing a multithreaded application?

    Thread behaving strangely in JUnit

    祝你好运!

    【讨论】:

      【解决方案2】:

      我认为既然你没有启动线程(Runnable你定义的对象),所以run方法永远不会被执行。您必须为要执行的 run 方法启动线程。

      【讨论】:

      • 你确定吗?因为如果我正在运行我的应用程序,相同的代码可以正常工作。但是如果我通过 jUnit 测试调用,那么只有它不起作用..
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2019-12-15
      • 1970-01-01
      • 2014-01-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多