从jUnit测试中调用方法

时间:2013-09-05 19:49:29

标签: java junit

下面是我的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");
}

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

2 个答案:

答案 0 :(得分:0)

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

答案 1 :(得分:0)

getBundlesInformation()方法正在另一个线程上运行,所以谁说它在断言方法或测试后没有运行?无论哪种方式,似乎问题都是尝试Junit测试线程应用程序。

您可能希望查看使用不同线程的Junit测试。我个人从来没有这样做,但经过快速谷歌搜索后,似乎它不是一个非常简单的任务,它可能更容易避免它/打破测试,所以他们不必处理不同的线程。

很抱歉,如果这个答案没有多大帮助 - 如果有经验的人看到这个,请尝试给出更好的答案!

一些快速搜索让我:

Unit testing a multithreaded application?

Thread behaving strangely in JUnit

祝你好运!