Sonarqube не принимает мой тест, но он работает в моем Eclipse - PullRequest
1 голос
/ 07 января 2020

У меня есть следующий код. Создает цифровые часы за 10 секунд. И когда я делаю коммит в git, SonarQube говорит, что все мои тесты провалились там. Но он работает на моем P C: \

public final class Clock implements Runnable {

    private static final org.slf4j.Logger LOGGER = LoggerFactory.getLogger(Clock.class);
    private static JFrame                 frame  = new JFrame();
    private final Font                    clockFont;
    private volatile boolean              flag   = true;


    /**
     * Clock constructor.
     */

    public Clock() {

        Clock.frame.setSize(1000, 250);
        Clock.frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        Clock.frame.setVisible(true);
        Clock.frame.setResizable(false);

        this.clockFont = new Font("Serif", Font.BOLD, 40);

        final Container contentArea = Clock.frame.getContentPane();
        final ClockPanel timeDisplay = new ClockPanel();

        contentArea.add(timeDisplay);
        Clock.frame.setContentPane(contentArea);

    }

Основной метод


    public static void main(final String[] args) {
        final Clock clock = new Clock();
        final Thread thread = new Thread(clock);
        thread.start();
        try {
            Thread.sleep(10000);
        } catch (final InterruptedException e) {
            Thread.currentThread().interrupt();
            Clock.LOGGER.info("Interrupted Exception was thrown", e);
        }

        clock.stopRunning();
        Clock.LOGGER.info("program was successfully executed");
    }

метод timeWashington

    public static String timeWashington() {

        final Calendar now = Calendar.getInstance();
        now.setTimeZone(TimeZone.getTimeZone("GMT-8"));

        final String month = new SimpleDateFormat("M", Locale.ENGLISH).format(now.getTime());
        final int date = now.get(Calendar.DATE);
        final int hrs = now.get(Calendar.HOUR_OF_DAY);
        final int min = now.get(Calendar.MINUTE);
        final int sec = now.get(Calendar.SECOND);

        return date + ", " + month + ", " + hrs + ":" + min + ":" + sec + " - Washington";
    }

и продолжение кода

    @Override
    public void run() {

        while (this.flag) {
            Clock.frame.repaint();

            try {
                Thread.sleep(1000);

            } catch (final InterruptedException e) {
                Thread.currentThread().interrupt();
                Clock.LOGGER.info("Interrupted Exception was thrown", e);
            }

        }
        Clock.frame.setVisible(false);
        Clock.frame.dispose();

    }

    /**
     * stopRunning method.
     */
    public void stopRunning() {
        this.flag = false;
    }

    /**
     * The ClockPanel fills current panel
     */
    class ClockPanel extends JPanel {

        private static final long serialVersionUID = 1L;

        @Override
        public void paintComponent(final Graphics painter) {

            painter.setFont(Clock.this.clockFont);
            painter.setColor(Color.black);
            painter.drawString(Clock.timeWashington(), 40, 40);
        }
    }

}

А мои тесты Junit следующие:

public class ClockTest {

    @Rule
    public final SystemOutRule log = new SystemOutRule().enableLog();

    @Test
    public void testMain() throws InterruptedException {
        final String[] args = null;
        Clock.main(args);
        Assert.assertEquals("it should be  equal", "program was successfully executed",
                this.log.getLog());
    }

    @Test
    public void testTimeWashington() {

        boolean result = false;
        final String time = Clock.timeWashington();
        if ((time != null) && !time.isEmpty()) {
            result = true;
        }

        Assert.assertTrue("This will succeed.", result);
    }
}

Скажите, пожалуйста, как я могу это исправить.

Не удалось ClockTest.testRunClock

Последние 1 сборка не удалась (с Unstable # 288). Потребовалось 2 мс.

Сообщение об ошибке Не удалось инициализировать класс by.iba.gomel.Clock Стек вызовов:

java.lang.NoClassDefFoundError: Could not initialize class by.iba.gomel.Clock
    at by.iba.gomel.ClockTest.testRunClock(ClockTest.java:16)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:50)
    at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
    at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:47)
    at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:17)
    at org.junit.contrib.java.lang.system.internal.LogPrintStream$1$1.evaluate(LogPrintStream.java:30)
    at org.junit.contrib.java.lang.system.internal.PrintStreamHandler$3.evaluate(PrintStreamHandler.java:48)
    at org.junit.contrib.java.lang.system.internal.LogPrintStream$1.evaluate(LogPrintStream.java:26)
    at org.junit.rules.RunRules.evaluate(RunRules.java:20)
    at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:325)
    at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:78)
    at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:57)
    at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290)
    at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71)
    at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288)
    at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58)
    at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268)
    at org.junit.runners.ParentRunner.run(ParentRunner.java:363)
    at org.apache.maven.surefire.junit4.JUnit4Provider.execute(JUnit4Provider.java:252)
    at org.apache.maven.surefire.junit4.JUnit4Provider.executeTestSet(JUnit4Provider.java:141)
    at org.apache.maven.surefire.junit4.JUnit4Provider.invoke(JUnit4Provider.java:112)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at org.apache.maven.surefire.util.ReflectionUtils.invokeMethodWithArray(ReflectionUtils.java:189)
    at org.apache.maven.surefire.booter.ProviderFactory$ProviderProxy.invoke(ProviderFactory.java:165)
    at org.apache.maven.surefire.booter.ProviderFactory.invokeProvider(ProviderFactory.java:85)
    at org.apache.maven.surefire.booter.ForkedBooter.runSuitesInProcess(ForkedBooter.java:115)
    at org.apache.maven.surefire.booter.ForkedBooter.main(ForkedBooter.java:75)

1 Ответ

0 голосов
/ 07 января 2020

Кажется, проблема root в том, что ваш тест ищет класс 'Clock':

java.lang.NoClassDefFoundError: Could not initialize class by.iba.gomel.Clock

Но ваша реализация Clock1

Это означает, что где ваши тесты устарели по сравнению с вашим локальным компьютером.

(т. е. переименование из Clock в Clock1 или связанное с ним обновление в вашем тестовом примере не привело к тому, что ваш тест выполняется)

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...