Junit4 intellij idea как установить
Перейти к содержимому

Junit4 intellij idea как установить

  • автор:

Почему JUnit не подключается к проекту IDEA?

Пытаюсь подключить JUnit к проекту, делаю по многочисленным одинаковым инструкциям:
Alt+Enter > Create test > выбираю JUnit, кликаю FIX, скачиваю.
Создатеся файл с классом, но import org.junit говорит: Unresolved reference.
Далее по инструкции создаю метод с аннотацией @Test, снова кликаю Alt+Enter, но add JUnit to classpath не появляется в отличии от скринов из туториалов, выдает только rename reference.

P.S: пробовал и с JUnit4, и с Junit5. Хочется решить без gradle. Нужно. Просто. Запустить. Тесты. Да, скоро я и gradle изучу, но не сейчас.

  • Вопрос задан более трёх лет назад
  • 720 просмотров

Комментировать

Решения вопроса 0

Ответы на вопрос 1

alfss

https://career.habr.com/alfss

Начинайте лучше сразу с gradle, незачем заниматься таким

Ответ написан более трёх лет назад

Комментировать

Нравится Комментировать

Ваш ответ на вопрос

Войдите, чтобы написать ответ

android

  • Android
  • +2 ещё

Как вернуть результат voice recognizer?

  • 1 подписчик
  • 16 часов назад
  • 28 просмотров

Не могу запустить тесты junit4 через консоль Linux

Написал тесты на junit4 с помощью intellij idea. Вот дерево тестов введите сюда описание изображения Раньше запускал тесты через intellij idea, теперь задача стоит в том, чтобы тесты запускались через консоль в Linux Mint. Подскажите пожалуйста, как это сделать?

Отслеживать

Ruslan Ismailov

задан 27 окт 2016 в 15:20

Ruslan Ismailov Ruslan Ismailov

1 4 4 бронзовых знака

$ java -cp /home/ruslan/Programms/junit-4.9b3.jar:/home/ruslan/IdeaProjects/AllTests/src/test/java/Accounting/Journal/ org.junit.runner.JUnitCore IdeaProjects.AllTests.src.test.java.Accounting.FirstTimeLogin — Выдает следующее: JUnit version 4.9b3 Could not find class: IdeaProjects.AllTests.src.test.java.Accounting.FirstTimeLogin Time: 0.001 OK (0 tests)

27 окт 2016 в 16:11

А если пишу так: $ java -cp .:/home/ruslan/Programms/junit-4.9b3.jar org.junit.runner.JUnitCore FirstTimeLogin то пишет: JUnit version 4.9b3 Could not find class: FirstTimeLogin Time: 0.001 OK (0 tests)

JUnit 5

In this tutorial, you will learn how to set up JUnit for your projects, create tests, and run them to see if your code is operating correctly. It contains just the basic steps to get you started.

If you want to know more about JUnit, refer to the official documentation. To learn more about testing features of IntelliJ IDEA, refer to other topics in this section.

You can choose to follow the tutorial using either Maven or Gradle.

Create a project

  1. Go to File | New | Project .
  2. Select New Project . Specify the name for the project, for example, junit-tutorial .
  3. Select Maven as a build tool. In Language , select Java .
  4. From the JDK list, select the JDK that you want to use in your project. If the JDK is installed on your computer, but not defined in the IDE, select Add JDK and specify the path to the JDK home directory. If you don’t have the necessary JDK on your computer, select Download JDK .
  5. Click Create .

For more information about working with Maven projects, refer to Maven.

Add dependencies

For our project to use JUnit features, we need to add JUnit as a dependency.

  1. Open pom.xml in the root directory of your project. To quickly navigate to a file, press Control+Shift+N and enter its name.
  2. In pom.xml , press Alt+Insert and select Dependency .
  3. In the dialog that opens, type org.junit.jupiter:junit-jupiter in the search field. Locate the necessary dependency in the search results and click Add .
  4. When the dependency is added to pom.xml , press Control+Shift+O or click in the Maven tool window to import the changes.

Create a project

  1. Go to File | New | Project .
  2. Select New Project . Specify the name for the project, for example, junit-tutorial .
  3. Select Gradle as a build tool. In Language , select Java .
  4. From the JDK list, select the JDK that you want to use in your project. If the JDK is installed on your computer, but not defined in the IDE, select Add JDK and specify the path to the JDK home directory. If you don’t have the necessary JDK on your computer, select Download JDK .
  5. Click Create .

For more information about working with Gradle projects, refer to Gradle.

Add dependencies

For our project to use JUnit features, we need to add JUnit as a dependency.

  1. Open build.gradle in the root directory of your project. To quickly navigate to a file, press Control+Shift+N and enter its name.
  2. In build.gradle , press Alt+Insert and select Add Maven artifact dependency .
  3. In the tool window that opens, type org.junit.jupiter:junit-jupiter in the search field. Locate the necessary dependency in the search results and click Add .
  4. When the dependency is added to build.gradle , press Control+Shift+O or click in the Gradle tool window to import the changes.

Create a project

  1. Go to File | New | Project .
  2. Select New Project . Specify the name for the project, for example, junit-tutorial .
  3. Select IntelliJ as a build tool. In Language , select Java .
  4. From the JDK list, select the JDK that you want to use in your project. If the JDK is installed on your computer, but not defined in the IDE, select Add JDK and specify the path to the JDK home directory. If you don’t have the necessary JDK on your computer, select Download JDK .
  5. Click Create .

Add dependencies

For our project to use JUnit features, we need to add JUnit as a dependency.

Manually adding a testing library to a project

  1. Go to File | Project Structure ( Control+Alt+Shift+S ) or click on the toolbar.
  2. Under Project Settings , select Libraries and click | From Maven .
  3. In the dialog that opens, specify the necessary library artifact, for example: org.junit.jupiter:junit-jupiter:5.9.1 .
  4. Click Apply to save the changes and close the dialog.

The procedure above shows the ‘manual’ way so that you know what happens behind the scenes and where you set up the testing framework. However, if you just start writing tests, IntelliJ IDEA will automatically detect if the dependency is missing and prompt you to add it.

Write application code

Let’s add some code that we’ll be testing.

  1. In the Project tool window Alt+1 , go to src/main/java and create a Java file called Calculator.java .
  2. Paste the following code in the file:

Create tests

Now let’s create a test. A test is a piece of code whose function is to check if another piece of code is operating correctly. In order to do the check, it calls the tested method and compares the result with the predefined expected result . An expected result can be, for example, a specific return value or an exception.

  1. Place the caret at the Calculator class declaration and press Alt+Enter . Alternatively, right-click it and select Show Context Actions . From the menu, select Create Test . The code of the class that we are going to test
  2. Select the two class methods that we are going to test. The Create Test dialog
  3. The editor takes you to the newly created test class. Modify the add() test as follows:

@Test @DisplayName(«Add two numbers») void add() < assertEquals(4, Calculator.add(2, 2)); >

@Test @DisplayName(«Multiply two numbers») void multiply() < assertAll(() ->assertEquals(4, Calculator.multiply(2, 2)), () -> assertEquals(-4, Calculator.multiply(2, -2)), () -> assertEquals(4, Calculator.multiply(-2, -2)), () -> assertEquals(0, Calculator.multiply(1, 0))); >

To navigate between the test and the code being tested, use the Control+Shift+T shortcut.

Run tests and view their results

After we have set up the code for the testing, we can run the tests and find out if the tested methods are working correctly.

The popup that appears after clicking on the Run icon in the gutter

  • To run an individual test, click in the gutter and select Run .
  • To run all tests in a test class, click against the test class declaration and select Run .

You can view test results in the Run tool window.

The results of the tests shown in the Run tool window

IntelliJ IDEA hides passed tests by default. To see them, make sure the Show Passed option is enabled in the Run tool window.

Force IntelliJ IDEA to use junit4 to run ‘All Tests’

I am using IntelliJ IDEA 2019.3.5 (Community Edition) and all my test cases are against Junit 4 and it’s was working fine. Recently I am getting errors like these.

java.lang.NoClassDefFoundError: org/junit/platform/launcher/TestExecutionListener java.lang.ClassNotFoundException: org.junit.platform.launcher.TestExecutionListener 

I got to know that Junit 5 expects these classes but my code is not Junit-5-ready. I cannot migrate to JUnit 5 as I think this can be handled at IDE level. Also, the test cases work fine with mvn commands outside the IDE using java 8. I found IDE running this command to run ‘All Tests’

/Library/Java/JavaVirtualMachines/jdk1.8.0_201.jdk/Contents/Home/bin/java -agentlib:jdwp=transport=dt_socket,address=127.0.0.1:54748,suspend=y,server=n -ea -Didea.test.cyclic.buffer.size=1048576 -javaagent:/Library/Caches/IdeaIC2019.3/captureAgent/debugger-agent.jar -Dfile.encoding=UTF-8 -classpath "/Applications/IntelliJ IDEA CE.app/Contents/lib/idea_rt.jar:/Applications/IntelliJ IDEA CE.app/Contents/plugins/junit/lib/junit5-rt.jar. " -ideVersion5 -junit5 @w@/private/var/folders/qr/mm80vkf55_qct4dffc662nhcz2kj03/T/idea_working_dirs_junit.tmp @/private/var/folders/qr/mm80vkf55_qct4dffc662nhcz2kj03/T/idea_junit.tmp -socket54747 

Can I force IntelliJ to run test cases using JUnit 4 only? FYI: I am using maven and bundled JUnit plugin with Intellij IDEA 2019.3.5 (Community Edition)

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *