Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Develop1 #919

Open
wants to merge 4 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from 2 commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
39 changes: 39 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
target/
!.mvn/wrapper/maven-wrapper.jar
!**/src/main/**/target/
!**/src/test/**/target/

### IntelliJ IDEA ###
.idea/
.idea/modules.xml
.idea/jarRepositories.xml
.idea/compiler.xml
.idea/libraries/
*.iws
*.iml
*.ipr

### Eclipse ###
.apt_generated
.classpath
.factorypath
.project
.settings
.springBeans
.sts4-cache

### NetBeans ###
/nbproject/private/
/nbbuild/
/dist/
/nbdist/
/.nb-gradle/
build/
!**/src/main/**/build/
!**/src/test/**/build/

### VS Code ###
.vscode/

### Mac OS ###
.DS_Store
14 changes: 14 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
<h1>Задание 1: юнит-тесты</h1>

<p>Нужно протестировать&nbsp;программу, которая помогает заказать бургер в Stellar Burgers. Предстоит покрыть её юнит-тестами.</p>

<p><a href="https://stellarburgers.nomoreparties.site/" rel="nofollow">Ссылка</a>&nbsp;на учебное приложение Stellar Burgers.</p>

<h3>Что сделано</h3>

<p>Склониран&nbsp;<a href="https://github.com/yandex-praktikum/QA-java-diplom-1" target="_blank">репозиторий</a> с заготовкой кода.</p>

<p>Подключены&nbsp;библиотеки: Jacoco, Mockito, JUnit 4.</p>

<p>Покрыты тестами классы Bun, Burger, Ingredient, IngredientType. Использованы моки, стабы и параметризация.</p>

57 changes: 54 additions & 3 deletions pom.xml
Original file line number Diff line number Diff line change
Expand Up @@ -3,14 +3,65 @@
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>

<groupId>org.example</groupId>
<artifactId>praktikum</artifactId>
<artifactId>QA-java-diplom-1</artifactId>
<version>1.0-SNAPSHOT</version>

<properties>
<maven.compiler.source>11</maven.compiler.source>
<maven.compiler.target>11</maven.compiler.target>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<junit-4.version>4.13.2</junit-4.version>
<byte-buddy.version>1.15.11</byte-buddy.version>
<mockito-core.version>5.14.2</mockito-core.version>
<jacoco.version>0.8.12</jacoco.version>
</properties>

</project>
<dependencies>
<dependency>
<groupId>org.mockito</groupId>
<artifactId>mockito-core</artifactId>
<version>${mockito-core.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>net.bytebuddy</groupId>
<artifactId>byte-buddy</artifactId>
<version>${byte-buddy.version}</version>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>${junit-4.version}</version>
<scope>test</scope>
</dependency>
</dependencies>

<build>
<sourceDirectory>src/main/java</sourceDirectory>
<plugins>
<plugin>
<groupId>org.jacoco</groupId>
<artifactId>jacoco-maven-plugin</artifactId>
<version>${jacoco.version}</version>
<executions>
<execution>
<id>prepare-agent</id>
<phase>initialize</phase>
<goals>
<goal>prepare-agent</goal>
</goals>
</execution>
<execution>
<id>report</id>
<phase>verify</phase>
<goals>
<goal>report</goal>
</goals>
</execution>
</executions>
</plugin>
</plugins>
</build>

</project>
47 changes: 47 additions & 0 deletions src/test/java/BunTest.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,47 @@
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.Parameterized;
import praktikum.Bun;

import static org.junit.Assert.assertEquals;

@RunWith(Parameterized.class)
public class BunTest {
private final String name;
private final float price;
private Bun bun;

public BunTest(String name, float price) {
this.name = name;
this.price = price;
}

@Parameterized.Parameters(name = "Название и цена булочки: {0}: {1}")
public static Object[][] getBunData() {
return new Object[][]{
{"Краторная булка N-200i", Float.MIN_VALUE},
{"Флюоресцентная булка R2-D3", Float.MAX_VALUE},
{" ", 1234},
{null, -123},
{"Zero price bun", 0.0f},
{"Обычная булка", 100.50f}
};
}

@Before
public void setUp() {
bun = new Bun(name, price);
}

@Test
public void getNameTest() {
assertEquals("Значение Имя не верное",name, bun.getName());
}

@Test
public void getPriceTest() {
assertEquals("Значение Цена не верное", price, bun.getPrice(), 0);
}

}
127 changes: 127 additions & 0 deletions src/test/java/BurgerTest.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,127 @@
import org.junit.Before;
import org.junit.Test;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.MockitoAnnotations;
import praktikum.*;

import static org.junit.Assert.assertEquals;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;

public class BurgerTest {
private static final String BUN_NAME = "new bun";
private static final float BUN_PRICE = 199.99F;
private static final String INGREDIENT_NAME = "new ingredient";
private static final float INGREDIENT_PRICE = 0.99F;

@InjectMocks
Burger burger;

@Mock
Bun bun;
Ingredient ingredientSauce;

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⛔️Нужно исправить. Пропущена аннотация @mock для ingredientSauce

Ingredient ingredientFilling;

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⛔️Нужно исправить. Пропущена аннотация @mock для ingredientFilling. Ожидала, что тут тоже проставишь)


@Before
public void setUp() throws Exception {
// Создаем моки
MockitoAnnotations.openMocks(this);
bun = getBunMock(BUN_NAME, BUN_PRICE);
ingredientSauce = getIngredientMock(IngredientType.SAUCE, INGREDIENT_NAME, INGREDIENT_PRICE);
ingredientFilling = getIngredientMock(IngredientType.FILLING, INGREDIENT_NAME, INGREDIENT_PRICE);
}

// Метод для создания мока булочки
private static Bun getBunMock(String name, float price) {
Bun bun = mock(Bun.class);
when(bun.getName()).thenReturn(name);
when(bun.getPrice()).thenReturn(price);
return bun;
}

// Метод для создания мока ингредиента
private static Ingredient getIngredientMock(IngredientType type, String name, float price) {
Ingredient ingredient = mock(Ingredient.class);
when(ingredient.getType()).thenReturn(type);
when(ingredient.getName()).thenReturn(name);
when(ingredient.getPrice()).thenReturn(price);
return ingredient;
}

@Test
public void setBunsWithMockTest() {
burger.setBuns(bun);
assertEquals(bun, burger.bun);
}

@Test
public void addIngredientWithTwoMockIngredientsTest() {
burger.addIngredient(ingredientSauce);
burger.addIngredient(ingredientFilling);
assertEquals("Количество ингредиентов в бургере указано не верно", 2, burger.ingredients.size());
}

@Test
public void removeIngredientWithMockIngredientTest() {
burger.addIngredient(ingredientSauce);
burger.removeIngredient(0);
assertEquals("Ингредиент не удален", 0, burger.ingredients.size());
}

@Test(expected = IndexOutOfBoundsException.class)
public void removeIngredientWithInvalidIndexThrowsExceptionTest() {
burger.removeIngredient(0); // Пустой список ингредиентов
}

@Test
public void moveIngredientWithMockTest() {
burger.addIngredient(ingredientSauce);
burger.addIngredient(ingredientFilling);
burger.moveIngredient(0, 1);
assertEquals("Ингредиенты не меняются местами", ingredientFilling, burger.ingredients.get(0));
}

@Test
public void moveIngredientWithMockTest2() {
burger.addIngredient(ingredientSauce);
burger.addIngredient(ingredientFilling);
burger.moveIngredient(0, 1);
assertEquals("Ингредиенты не меняются местами", ingredientSauce, burger.ingredients.get(1));
}

@Test(expected = IndexOutOfBoundsException.class)
public void moveIngredientWithInvalidIndexThrowsExceptionTest() {
burger.moveIngredient(0, 1); // Пустой список ингредиентов
}

@Test
public void getPriceWithMockTest() {
burger.setBuns(bun);
burger.addIngredient(ingredientSauce);
burger.addIngredient(ingredientFilling);
float expectedPrice = BUN_PRICE * 2 + INGREDIENT_PRICE * 2;
assertEquals("Цена бургера не корректна", expectedPrice, burger.getPrice(), 0.001F);
}

@Test
public void getReceiptWithMockTest() {
burger.setBuns(bun);
burger.addIngredient(ingredientSauce);
burger.addIngredient(ingredientFilling);

String expected = String.format(
"(==== %s ====)%n" +
"= %s %s =%n" +
"= %s %s =%n" +
"(==== %s ====)%n" +
"%nPrice: %f%n",
BUN_NAME,
IngredientType.SAUCE.toString().toLowerCase(), INGREDIENT_NAME,
IngredientType.FILLING.toString().toLowerCase(), INGREDIENT_NAME,
BUN_NAME,
burger.getPrice());

assertEquals("Рецепт напечатан не верно", expected, burger.getReceipt());
}
}
54 changes: 54 additions & 0 deletions src/test/java/IngredientTest.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,54 @@
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.Parameterized;
import praktikum.*;

import static org.junit.Assert.assertEquals;


@RunWith(Parameterized.class)
public class IngredientTest {
private final String name;
private final float price;
private final IngredientType type;
private Ingredient ingredient;

public IngredientTest(IngredientType type, String name, float price) {
this.type = type;
this.name = name;
this.price = price;
}

@Parameterized.Parameters(name = "Тип ингридиента, название, цена : {0}: {1}: {2}")
public static Object[][] testsData() {
return new Object[][]{
{IngredientType.SAUCE, "Соус Spicy-X", Float.MAX_VALUE},
{IngredientType.FILLING, "Мясо бессмертных моллюсков Protostomia", Float.MIN_NORMAL},
{IngredientType.SAUCE, " ", Float.MIN_VALUE},
{IngredientType.FILLING, null, -123},
{null, null, 0}
};
}

@Before
public void setup() {
ingredient = new Ingredient(type, name, price);
}

@Test
public void getTypeWithValidDataTest() {
assertEquals("Значение Тип ингридиент неверное", type, ingredient.getType());
}

@Test
public void getNameWithValidDataTest() {
assertEquals("Значение Имя неверное", name, ingredient.getName());
}

@Test
public void getPriceWithValidDataTest() {
assertEquals("Значение Цена неверное", price, ingredient.getPrice(), 0);
}

}
31 changes: 31 additions & 0 deletions src/test/java/IngredientTypeTest.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.Parameterized;
import praktikum.IngredientType;

import static org.junit.Assert.assertEquals;


@RunWith(Parameterized.class)
public class IngredientTypeTest {
private final IngredientType type;
private final String name;

public IngredientTypeTest(IngredientType type, String name) {
this.type = type;
this.name = name;
}

@Parameterized.Parameters(name = "Тип ингредиента: {0}: {1}")
public static Object[][] getIngredientTypeData() {
return new Object[][] {
{IngredientType.SAUCE, "SAUCE"},
{IngredientType.FILLING, "FILLING"}
};
}

@Test
public void getIngredientTypeNameTest() {
assertEquals("Неправильное название типа ингредиента", name, type.name());
}
}
1 change: 1 addition & 0 deletions target/site/jacoco/index.html
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
<?xml version="1.0" encoding="UTF-8"?><!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"><html xmlns="http://www.w3.org/1999/xhtml" lang="ru"><head><meta http-equiv="Content-Type" content="text/html;charset=UTF-8"/><link rel="stylesheet" href="jacoco-resources/report.css" type="text/css"/><link rel="shortcut icon" href="jacoco-resources/report.gif" type="image/gif"/><title>untitled</title><script type="text/javascript" src="jacoco-resources/sort.js"></script></head><body onload="initialSort(['breadcrumb', 'coveragetable'])"><div class="breadcrumb" id="breadcrumb"><span class="info"><a href="jacoco-sessions.html" class="el_session">Sessions</a></span><span class="el_report">untitled</span></div><h1>untitled</h1><table class="coverage" cellspacing="0" id="coveragetable"><thead><tr><td class="sortable" id="a" onclick="toggleSort(this)">Element</td><td class="down sortable bar" id="b" onclick="toggleSort(this)">Missed Instructions</td><td class="sortable ctr2" id="c" onclick="toggleSort(this)">Cov.</td><td class="sortable bar" id="d" onclick="toggleSort(this)">Missed Branches</td><td class="sortable ctr2" id="e" onclick="toggleSort(this)">Cov.</td><td class="sortable ctr1" id="f" onclick="toggleSort(this)">Missed</td><td class="sortable ctr2" id="g" onclick="toggleSort(this)">Cxty</td><td class="sortable ctr1" id="h" onclick="toggleSort(this)">Missed</td><td class="sortable ctr2" id="i" onclick="toggleSort(this)">Lines</td><td class="sortable ctr1" id="j" onclick="toggleSort(this)">Missed</td><td class="sortable ctr2" id="k" onclick="toggleSort(this)">Methods</td><td class="sortable ctr1" id="l" onclick="toggleSort(this)">Missed</td><td class="sortable ctr2" id="m" onclick="toggleSort(this)">Classes</td></tr></thead><tfoot><tr><td>Total</td><td class="bar">165 of 358</td><td class="ctr2">53 %</td><td class="bar">0 of 4</td><td class="ctr2">100 %</td><td class="ctr1">5</td><td class="ctr2">22</td><td class="ctr1">29</td><td class="ctr2">69</td><td class="ctr1">5</td><td class="ctr2">20</td><td class="ctr1">2</td><td class="ctr2">6</td></tr></tfoot><tbody><tr><td id="a0"><a href="praktikum/index.html" class="el_package">praktikum</a></td><td class="bar" id="b0"><img src="jacoco-resources/redbar.gif" width="55" height="10" title="165" alt="165"/><img src="jacoco-resources/greenbar.gif" width="64" height="10" title="193" alt="193"/></td><td class="ctr2" id="c0">53 %</td><td class="bar" id="d0"><img src="jacoco-resources/greenbar.gif" width="120" height="10" title="4" alt="4"/></td><td class="ctr2" id="e0">100 %</td><td class="ctr1" id="f0">5</td><td class="ctr2" id="g0">22</td><td class="ctr1" id="h0">29</td><td class="ctr2" id="i0">69</td><td class="ctr1" id="j0">5</td><td class="ctr2" id="k0">20</td><td class="ctr1" id="l0">2</td><td class="ctr2" id="m0">6</td></tr></tbody></table><div class="footer"><span class="right">Created with <a href="http://www.jacoco.org/jacoco">JaCoCo</a> 0.8.12.202403310830</span></div></body></html>
Binary file added target/site/jacoco/jacoco-resources/branchfc.gif
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Binary file added target/site/jacoco/jacoco-resources/branchnc.gif
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Binary file added target/site/jacoco/jacoco-resources/branchpc.gif
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Binary file added target/site/jacoco/jacoco-resources/bundle.gif
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Binary file added target/site/jacoco/jacoco-resources/class.gif
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Binary file added target/site/jacoco/jacoco-resources/down.gif
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Binary file added target/site/jacoco/jacoco-resources/greenbar.gif
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Binary file added target/site/jacoco/jacoco-resources/group.gif
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Binary file added target/site/jacoco/jacoco-resources/method.gif
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Binary file added target/site/jacoco/jacoco-resources/package.gif
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Loading