Java hello world test

JUnit — введение в юнит-тесты. Пример JUnit Hello world

jUnitHelloStr

Класс Calculator описывает простые арифметические операции. Этот класс послужит основой для написания юнит тестов. Тестирующие классы находятся в пакете test .

3. pom.xml

Для подключения библиотеки JUnit используется maven.

xsi : schemaLocation = «http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd» >

Других зависимостей подключать не нужно.

4. Calculator

Наш простой класс, описывающий калькулятор описан чуть ниже.

5. Создание тестирующих классов

В IntelliJ IDEA можно создать тестирующих класс автоматически. Для этого можно нажать alt + enter на классе и выбрать «Create test». Далее выбрать методы, которые нужно будет протестировать. В результате будет создан класс CalculatorTest с тремя выбранными методами. Эти методы необходимо реализовать самостоятельно.

createTest

createTest2

6. CalculatorTest

После создания тестирующего класса нам необходимо реализовать методы, которые мы хотим проверить. Так же были добавлены другие методы, которые будут демонстрировать работу базовых JUnit аннотаций.

Источник

Saved searches

Use saved searches to filter your results more quickly

You signed in with another tab or window. Reload to refresh your session. You signed out in another tab or window. Reload to refresh your session. You switched accounts on another tab or window. Reload to refresh your session.

ppcololo/helloworld

This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.

Name already in use

A tag already exists with the provided branch name. Many Git commands accept both tag and branch names, so creating this branch may cause unexpected behavior. Are you sure you want to create this branch?

Sign In Required

Please sign in to use Codespaces.

Читайте также:  Nested if conditions in java

Launching GitHub Desktop

If nothing happens, download GitHub Desktop and try again.

Launching GitHub Desktop

If nothing happens, download GitHub Desktop and try again.

Launching Xcode

If nothing happens, download Xcode and try again.

Launching Visual Studio Code

Your codespace will open once ready.

There was a problem preparing your codespace, please try again.

Latest commit

Git stats

Files

Failed to load latest commit information.

README.md

Тестовое задание на написание веб-приложения helloworld

Реализовать тривиальное HTTP "Hello, world!" web-приложение на любом удобном Вам языке программирования и завернуть его в clound native окружение. Требования: - Dockerfile, который докеризует приложение. - Приложение должно иметь health-check и ready-check. - Приложение должно предоставлять metrics endpoint для Prometheus (метрики - на Ваше усмотрение). - Grafana dashboard с визуализацией метрик. - docker-compose.yml, который запускает приложение со всем необходимым окружением (Prometheus и Grafana). Временем и инструментом для выполнение тестового задания Вы не ограничены. Любые другие аспекты реализации, которые не указаны в требованиях, могут быть выполнены на Ваше усмотрение. Следующее будет плюсом: - Kubernetes спеки приложения, либо Helm-чарт, для запуска его в Minikube (в дополнение к docker-compose.yaml). - E2E-тесты, которые проверяют корректность докеризации приложения. 

Реализовано на языке Java (Spring Boot) Добавлена одна кастомная метрика requests_count_total — количество запросов главной страницы Собранный jar файл специально не клал рядом с кодом — много места ест.

Docker (шаги 0 и 1 можно пропустить, так как собранный образ с данным сервисом внутри уже лежит на dockerhub)

IntelliJ IDEA > Maven > package 

кладем jar-файл в папку docker

cd docker docker built -t helloworld . 
  1. Заходим и смотрим стартанувшие компоненты:
  • helloworld : localhost:8080 (metrics — localhost:8080/actuator/prometheus)
  • prometheus : localhost:9090
  • grafana : localhost:3000 (admin/admin)

В папке k8s/helloworld лежит helm chart для нашего сервиса.
Установка чарта описана в файлике README.md Там реализован deployment c сервисом helloworld + readiness\liveness probes.
Так же там есть ingress, но хост надо будет добавлять себе в /etc/hosts

PS: docker-image предварительно загружен в dockerhub

Источник

Saved searches

Use saved searches to filter your results more quickly

You signed in with another tab or window. Reload to refresh your session. You signed out in another tab or window. Reload to refresh your session. You switched accounts on another tab or window. Reload to refresh your session.

Читайте также:  Php if property is defined

java helloworld project with junit, no ide, only commandline

sgurjar/java-hello-world

This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.

Name already in use

A tag already exists with the provided branch name. Many Git commands accept both tag and branch names, so creating this branch may cause unexpected behavior. Are you sure you want to create this branch?

Sign In Required

Please sign in to use Codespaces.

Launching GitHub Desktop

If nothing happens, download GitHub Desktop and try again.

Launching GitHub Desktop

If nothing happens, download GitHub Desktop and try again.

Launching Xcode

If nothing happens, download Xcode and try again.

Launching Visual Studio Code

Your codespace will open once ready.

There was a problem preparing your codespace, please try again.

Latest commit

Git stats

Files

Failed to load latest commit information.

README.md

java helloworld project with junit, no ide, only commandline

$ mkdir helloworld-proj # create project dir $ cd helloworld-proj $ mkdir src/main # main source dir $ mkdir src/test # test (junit) source dir $ mkdir bin # shell/bat scripts to run $ mkdir lib # lib dir for jar files $ mkdir config # properties file etc $ mkdir build # compilation target dir 

copy following jar files in lib dir

$ ls lib junit-4.10.jar log4j-1.2.8.jar 
$ mkdir src/main/foo/bar $ vi src/main/foo/bar/HelloWorld.java 

write your code in HelloWorld.java

package foo.bar; import org.apache.log4j.Logger; import java.io.*; import java.util.*; public class HelloWorld < private static final Logger log = Logger.getLogger(HelloWorld.class); public boolean holaMundo() throws IOException < Properties conf = loadConfig(); String name = conf.getProperty("your.name"); if ((name == null) || name.isEmpty()) < throw new IOException("required config missing, 'your.name'"); >System.out.printf("Pronto %s%n", name); return true; > Properties loadConfig() throws IOException < String configfile = System.getProperty("configfile"); if (configfile == null) < throw new IOException("no configfile"); >log.info("configfile -1" dir="auto"> create a test case 

write junit testcase for it, make sure to use Test pattern as it will used in build.xml

$ mkdir src/test/foo/bar $ vi src/test/foo/bar/HelloWorldTest.java 

write your junit testcase in TestHelloWorld.java. We are writing junit4 testcase.

package foo.bar; import static org.junit.Assert.*; import org.junit.Test; public class HelloWorldTest < @Test public void testBonjourToutLeMonde() throws Exception < // test function name can be anything // @Test annotation makes it a test fuction HelloWorld hw = new HelloWorld(); boolean ok = hw.holaMundo(); assertTrue("Hellow world failed", ok); >> 

Write a build.xml that builds main and test source code and run junit testcase.

                ">  --> /log4j-1.2.8.jar" />  ">  --> /junit-4.10.jar" /> "/>  "/>  "/> "/>          "/>     Test format-->      "/> uncomment if you want to distribute source with jar file --> "/> -->     
$ cat config/helloworld-proj.conf your.name=Asia Argento 
$ ant -projecthelp Main targets: clean clean up compile.all Compiles all source code compile.main Compiles the main source code compile.test Compiles the test source code dist generate the distribution junit runs junit testcases Default target: compile.all $ ant init: prepare: [mkdir] Created dir: /helloworld-proj/build/main [mkdir] Created dir: /helloworld-proj/build/test compile.main: [javac] Compiling 1 source file to /helloworld-proj/build/main compile.test: [javac] Compiling 1 source file to /helloworld-proj/build/test compile.all: BUILD SUCCESSFUL Total time: 0 seconds $ ant junit init: prepare: compile.main: compile.test: junit: [mkdir] Created dir: /helloworld-proj/test_report [junit] Running foo.bar.HelloWorldTest [junit] Tests run: 1, Failures: 0, Errors: 1, Time elapsed: 0.073 sec BUILD FAILED /helloworld-proj/build.xml:85: Test foo.bar.HelloWorldTest failed Total time: 1 second $ cat test_report/TEST-foo.bar.HelloWorldTest.xml| java.io.IOException: no configfile at foo.bar.HelloWorld.loadConfig(HelloWorld.java:29) at foo.bar.HelloWorld.holaMundo(HelloWorld.java:12) at foo.bar.HelloWorldTest.testBonjourToutLeMonde(HelloWorldTest.java:13) 

We will have to cofigfile system property, update build.xml to add sysproperty to junit target

 "/> /config/helloworld-proj.conf"/> /config/helloworld-proj.log4j"/>      Test format--> " includes="**/*Test.java"/>   $ ant junit init: prepare: compile.main: compile.test: junit: [junit] Running foo.bar.HelloWorldTest [junit] Pronto Asia Argento [junit] Tests run: 1, Failures: 0, Errors: 0, Time elapsed: 0.102 sec BUILD SUCCESSFUL Total time: 1 second 

finally we will have dir struct like this

 | build.xml | +---bin +---build | +---main | | \---foo | | \---bar | | HelloWorld.class | | | \---test | \---foo | \---bar | HelloWorldTest.class | +---config | helloworld-proj.conf | helloworld-proj.log4j | +---lib | junit-4.10.jar | log4j-1.2.8.jar | +---src | +---main | | \---foo | | \---bar | | HelloWorld.java | | | \---test | \---foo | \---bar | HelloWorldTest.java | \---test_report TEST-foo.bar.HelloWorldTest.xml 

About

java helloworld project with junit, no ide, only commandline

Источник

Оцените статью