From eb8761ac4e3f337c342cb0c87d60085133bcdd1b Mon Sep 17 00:00:00 2001 From: Roman-M-git Date: Wed, 14 Jan 2026 10:30:20 +0200 Subject: [PATCH] Changed for pull request --- .idea/vcs.xml | 6 + pom.xml | 131 +++++++++++++---- src/main/java/com/javarush/App.java | 13 -- .../java/com/javarush/quest/GameServlet.java | 80 ++++++++++ .../java/com/javarush/quest/HelloServlet.java | 17 +++ .../java/com/javarush/quest/StartServlet.java | 33 +++++ .../javarush/quest/filter/EncodingFilter.java | 26 ++++ .../com/javarush/quest/model/QuestStep.java | 96 ++++++++++++ .../javarush/quest/service/QuestService.java | 95 ++++++++++++ src/main/webapp/WEB-INF/web.xml | 32 ++++ src/main/webapp/error404.jsp | 18 +++ src/main/webapp/error500.jsp | 24 +++ src/main/webapp/game.jsp | 138 ++++++++++++++++++ src/main/webapp/index.jsp | 110 ++++++++++++++ src/main/webapp/result.jsp | 18 +++ src/test/java/com/javarush/AppTest.java | 38 ----- .../com/javarush/quest/GameServletTest.java | 91 ++++++++++++ .../com/javarush/quest/StartServletTest.java | 62 ++++++++ .../quest/service/QuestServiceTest.java | 73 +++++++++ 19 files changed, 1025 insertions(+), 76 deletions(-) create mode 100644 .idea/vcs.xml delete mode 100644 src/main/java/com/javarush/App.java create mode 100644 src/main/java/com/javarush/quest/GameServlet.java create mode 100644 src/main/java/com/javarush/quest/HelloServlet.java create mode 100644 src/main/java/com/javarush/quest/StartServlet.java create mode 100644 src/main/java/com/javarush/quest/filter/EncodingFilter.java create mode 100644 src/main/java/com/javarush/quest/model/QuestStep.java create mode 100644 src/main/java/com/javarush/quest/service/QuestService.java create mode 100644 src/main/webapp/WEB-INF/web.xml create mode 100644 src/main/webapp/error404.jsp create mode 100644 src/main/webapp/error500.jsp create mode 100644 src/main/webapp/game.jsp create mode 100644 src/main/webapp/index.jsp create mode 100644 src/main/webapp/result.jsp delete mode 100644 src/test/java/com/javarush/AppTest.java create mode 100644 src/test/java/com/javarush/quest/GameServletTest.java create mode 100644 src/test/java/com/javarush/quest/StartServletTest.java create mode 100644 src/test/java/com/javarush/quest/service/QuestServiceTest.java diff --git a/.idea/vcs.xml b/.idea/vcs.xml new file mode 100644 index 0000000..94a25f7 --- /dev/null +++ b/.idea/vcs.xml @@ -0,0 +1,6 @@ + + + + + + \ No newline at end of file diff --git a/pom.xml b/pom.xml index 2446fa8..f917672 100644 --- a/pom.xml +++ b/pom.xml @@ -1,25 +1,106 @@ - - 4.0.0 - - com.javarush - SpaceQuestModule3 - 1.0-SNAPSHOT - jar - - SpaceQuestModule3 - http://maven.apache.org - - - UTF-8 - - - - - junit - junit - 3.8.1 - test - - - + + + 4.0.0 + + com.javarush + HelloQuest + 1.0-SNAPSHOT + war + + + 11 + 11 + UTF-8 + 5.9.2 + + + + + + + javax.servlet + javax.servlet-api + 4.0.1 + provided + + + + + javax.servlet + jstl + 1.2 + + + + + org.junit.jupiter + junit-jupiter + ${junit.version} + test + + + + + org.mockito + mockito-core + 5.6.0 + test + + + + + org.mockito + mockito-junit-jupiter + 5.6.0 + test + + + + + + + + + + org.apache.maven.plugins + maven-war-plugin + 3.3.2 + + + + + org.apache.maven.plugins + maven-compiler-plugin + 3.8.1 + + 11 + 11 + UTF-8 + + + + + + org.apache.tomcat.maven + tomcat7-maven-plugin + 2.2 + + 8080 + /HelloQuest + + + + + org.apache.maven.plugins + maven-surefire-plugin + 3.0.0-M7 + + + + + + + \ No newline at end of file diff --git a/src/main/java/com/javarush/App.java b/src/main/java/com/javarush/App.java deleted file mode 100644 index 6d0055f..0000000 --- a/src/main/java/com/javarush/App.java +++ /dev/null @@ -1,13 +0,0 @@ -package com.javarush; - -/** - * Hello world! - * - */ -public class App -{ - public static void main( String[] args ) - { - System.out.println( "Hello World!" ); - } -} diff --git a/src/main/java/com/javarush/quest/GameServlet.java b/src/main/java/com/javarush/quest/GameServlet.java new file mode 100644 index 0000000..f6097b8 --- /dev/null +++ b/src/main/java/com/javarush/quest/GameServlet.java @@ -0,0 +1,80 @@ +package com.javarush.quest; + +import com.javarush.quest.model.QuestStep; +import com.javarush.quest.service.QuestService; + +import javax.servlet.ServletException; +import javax.servlet.annotation.WebServlet; +import javax.servlet.http.HttpServlet; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; +import javax.servlet.http.HttpSession; +import java.io.IOException; + +@WebServlet("/game") +public class GameServlet extends HttpServlet { + + private final QuestService questService = new QuestService(); + + @Override + protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { + String stepId = req.getParameter("step"); + if (stepId == null || stepId.isEmpty()) { + stepId = "start"; + } + + QuestStep step = questService.getStep(stepId); + if (step == null) { + resp.sendError(HttpServletResponse.SC_NOT_FOUND, "Шаг не найден!"); + } + + req.setAttribute("step", step); + req.getRequestDispatcher("/game.jsp").forward(req, resp); + + } + + + @Override + protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { + HttpSession session = req.getSession(); + + // Получаем параметры + String answer = req.getParameter("answer"); + String currentStepId = req.getParameter("currentStep"); + + // Валидация + if (answer == null || currentStepId == null) { + resp.sendRedirect(req.getContextPath() + "/game?step=start"); + return; + } + + // Получить текущий шаг + QuestStep currentStep = questService.getStep(currentStepId); + if (currentStep == null) { + resp.sendRedirect(req.getContextPath() + "/game?step=start"); + return; + } + + // Cлед шаг + String nextStepId; + if ("1".equals(answer)) { + nextStepId = currentStep.getNextStepId1(); + } else { + nextStepId = currentStep.getNextStepId2(); + } + + // Обновляем статистику + if (questService.isFinalStep(nextStepId)) { + Integer gamesPlayed = (Integer) session.getAttribute("gamesPlayed"); + if (gamesPlayed == null) { + gamesPlayed = 0; + } + session.setAttribute("gamesPlayed", gamesPlayed + 1); + } + + // на след шаг + resp.sendRedirect(req.getContextPath() + "/game?step=" + nextStepId); + + } + +} \ No newline at end of file diff --git a/src/main/java/com/javarush/quest/HelloServlet.java b/src/main/java/com/javarush/quest/HelloServlet.java new file mode 100644 index 0000000..7be8f31 --- /dev/null +++ b/src/main/java/com/javarush/quest/HelloServlet.java @@ -0,0 +1,17 @@ +package com.javarush.quest; + +import javax.servlet.ServletException; +import javax.servlet.annotation.WebServlet; +import javax.servlet.http.HttpServlet; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; +import java.io.IOException; + +@WebServlet("/hello") +public class HelloServlet extends HttpServlet { + @Override + protected void doGet(HttpServletRequest req, HttpServletResponse resp) + throws ServletException, IOException { + req.getRequestDispatcher("/index.jsp").forward(req, resp); + } +} \ No newline at end of file diff --git a/src/main/java/com/javarush/quest/StartServlet.java b/src/main/java/com/javarush/quest/StartServlet.java new file mode 100644 index 0000000..e4c6c1b --- /dev/null +++ b/src/main/java/com/javarush/quest/StartServlet.java @@ -0,0 +1,33 @@ +package com.javarush.quest; + +import javax.servlet.ServletException; +import javax.servlet.annotation.WebServlet; +import javax.servlet.http.HttpServlet; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; +import javax.servlet.http.HttpSession; +import java.io.IOException; + +@WebServlet("/start") +public class StartServlet extends HttpServlet { + + @Override + protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { +request.getRequestDispatcher("/index.jsp").forward(request, response); + } + + + @Override + protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { + String playerName = request.getParameter("playerName"); + if (playerName == null || playerName.trim().isEmpty()) { + playerName = "Искатель приключений"; + } + HttpSession session = request.getSession(); + session.setAttribute("playerName", playerName); + session.setAttribute("gamesPlayed", 0); + + response.sendRedirect(request.getContextPath() + "/game?step=start"); + } + +} \ No newline at end of file diff --git a/src/main/java/com/javarush/quest/filter/EncodingFilter.java b/src/main/java/com/javarush/quest/filter/EncodingFilter.java new file mode 100644 index 0000000..e79959a --- /dev/null +++ b/src/main/java/com/javarush/quest/filter/EncodingFilter.java @@ -0,0 +1,26 @@ +package com.javarush.quest.filter; + +import javax.servlet.*; +import javax.servlet.annotation.WebFilter; +import java.io.IOException; + +@WebFilter("/*") +public class EncodingFilter implements Filter { + @Override + public void init(FilterConfig filterConfig) throws ServletException { + // Инициализация не требуется + } + + @Override + public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException { + servletRequest.setCharacterEncoding("UTF-8"); + servletResponse.setCharacterEncoding("UTF-8"); + servletResponse.setContentType("text/html;charset=UTF-8"); + filterChain.doFilter(servletRequest, servletResponse); + } + + @Override + public void destroy() { + // Очистка не треб. + } +} \ No newline at end of file diff --git a/src/main/java/com/javarush/quest/model/QuestStep.java b/src/main/java/com/javarush/quest/model/QuestStep.java new file mode 100644 index 0000000..316cce0 --- /dev/null +++ b/src/main/java/com/javarush/quest/model/QuestStep.java @@ -0,0 +1,96 @@ +package com.javarush.quest.model; + +import java.util.Objects; + +public class QuestStep { + private String id; + private String text; + private String option1; + private String option2; + private String nextStepId1; + private String nextStepId2; + + public QuestStep() { + } + + public QuestStep(String id, String text, String option1, String option2, String nextStepId1, String nextStepId2) { + this.id = id; + this.text = text; + this.option1 = option1; + this.option2 = option2; + this.nextStepId1 = nextStepId1; + this.nextStepId2 = nextStepId2; + } + + public String getId() { + return id; + } + + public void setId(String id) { + this.id = id; + } + + public String getText() { + return text; + } + + public void setText(String text) { + this.text = text; + } + + public String getOption1() { + return option1; + } + + public void setOption1(String option1) { + this.option1 = option1; + } + + public String getOption2() { + return option2; + } + + public void setOption2(String option2) { + this.option2 = option2; + } + + public String getNextStepId1() { + return nextStepId1; + } + + public void setNextStepId1(String nextStepId1) { + this.nextStepId1 = nextStepId1; + } + + public String getNextStepId2() { + return nextStepId2; + } + + public void setNextStepId2(String nextStepId2) { + this.nextStepId2 = nextStepId2; + } + + @Override + public boolean equals(Object object) { + if (object == null || getClass() != object.getClass()) return false; + QuestStep questStep = (QuestStep) object; + return Objects.equals(id, questStep.id) && Objects.equals(text, questStep.text) && Objects.equals(option1, questStep.option1) && Objects.equals(option2, questStep.option2) && Objects.equals(nextStepId1, questStep.nextStepId1) && Objects.equals(nextStepId2, questStep.nextStepId2); + } + + @Override + public int hashCode() { + return Objects.hash(id, text, option1, option2, nextStepId1, nextStepId2); + } + + @Override + public String toString() { + return "QuestStep{" + + "id='" + id + '\'' + + ", text='" + text + '\'' + + ", option1='" + option1 + '\'' + + ", option2='" + option2 + '\'' + + ", nextStepId1='" + nextStepId1 + '\'' + + ", nextStepId2='" + nextStepId2 + '\'' + + '}'; + } +} \ No newline at end of file diff --git a/src/main/java/com/javarush/quest/service/QuestService.java b/src/main/java/com/javarush/quest/service/QuestService.java new file mode 100644 index 0000000..eac9be9 --- /dev/null +++ b/src/main/java/com/javarush/quest/service/QuestService.java @@ -0,0 +1,95 @@ +package com.javarush.quest.service; + +import com.javarush.quest.model.QuestStep; + +import java.util.HashMap; +import java.util.Map; + +public class QuestService { + + private final Map steps = new HashMap<>(); + + public QuestService() { + initSteps(); + } + + private void initSteps() { + + // 1. Старт + steps.put("start", new QuestStep( + "start", + "Ты потерял память. Принять вызов НЛО?", + "Принять вызов", + "Отклонить вызов", + "bridge", // ← ИСПРАВЛЕНО (было: "accept") + "lose1" + )); + + // 2. Мостик + steps.put("bridge", new QuestStep( + "bridge", + "Ты принял вызов. Поднимаешься на мостик к капитану?", + "Подняться на мостик", + "Отказаться", + "captain", + "lose2" + )); + + // 3. Капитан + steps.put("captain", new QuestStep( + "captain", + "Ты поднялся на мостик. Ты кто?", + "Рассказать правду о себе", + "Солгать о себе", + "win", + "lose3" + )); + + // Победа + steps.put("win", new QuestStep( + "win", + "Тебя вернули домой. Победа!", + null, + null, + null, + null + )); + + // Поражения + steps.put("lose1", new QuestStep( + "lose1", + "Ты отклонил вызов. Поражение!", + null, + null, + null, + null + )); + + steps.put("lose2", new QuestStep( + "lose2", + "Ты не пошел на переговоры. Поражение!", + null, + null, + null, + null + )); + + steps.put("lose3", new QuestStep( + "lose3", + "Твоя ложь разоблачена. Поражение!", + null, + null, + null, + null + )); + } + + public QuestStep getStep(String id) { + return steps.get(id); + } + + public boolean isFinalStep(String stepId) { + QuestStep step = steps.get(stepId); + return step != null && step.getOption1() == null; + } +} \ No newline at end of file diff --git a/src/main/webapp/WEB-INF/web.xml b/src/main/webapp/WEB-INF/web.xml new file mode 100644 index 0000000..f8a1141 --- /dev/null +++ b/src/main/webapp/WEB-INF/web.xml @@ -0,0 +1,32 @@ + + + + HelloQuest(II) + + + index.jsp + + + + 30 + + true + + + + + + 404 + /error404.jsp + + + + 500 + /error500.jsp + + + \ No newline at end of file diff --git a/src/main/webapp/error404.jsp b/src/main/webapp/error404.jsp new file mode 100644 index 0000000..77b480f --- /dev/null +++ b/src/main/webapp/error404.jsp @@ -0,0 +1,18 @@ +<%-- + Created by IntelliJ IDEA. + User: rmeeo + Date: 25-Dec-25 + Time: 16:28 + To change this template use File | Settings | File Templates. +--%> +<%@ page contentType="text/html;charset=UTF-8" language="java" %> + + + 404 - Страница не найдена + + +

404 - Страница не найдена

+

Запрашиваемая страница не существует.

+

Вернуться на главную

+ + diff --git a/src/main/webapp/error500.jsp b/src/main/webapp/error500.jsp new file mode 100644 index 0000000..6084a78 --- /dev/null +++ b/src/main/webapp/error500.jsp @@ -0,0 +1,24 @@ +<%-- + Created by IntelliJ IDEA. + User: rmeeo + Date: 25-Dec-25 + Time: 16:29 + To change this template use File | Settings | File Templates. +--%> +<%@ page contentType="text/html;charset=UTF-8" language="java" %> +<%@ page isErrorPage="true" %> + + + 500 - Ошибка сервера + + +

500 - Ошибка сервера

+

Что-то пошло не так на нашей стороне.

+

Мы уже работаем над исправлением проблемы.

+ +

+ На главную | + Начать игру +

+ + diff --git a/src/main/webapp/game.jsp b/src/main/webapp/game.jsp new file mode 100644 index 0000000..e4f2fd7 --- /dev/null +++ b/src/main/webapp/game.jsp @@ -0,0 +1,138 @@ +<%-- + Created by IntelliJ IDEA. + User: rmeeo + Date: 25-Dec-25 + Time: 15:53 + To change this template use File | Settings | File Templates. +--%> +<%@ page contentType="text/html;charset=UTF-8" language="java" %> +<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %> + + + Космический квест + + + + + +

Космический квест

+ +
+

Игрок: ${sessionScope.playerName}

+

Сыграно игр: ${sessionScope.gamesPlayed != null ? sessionScope.gamesPlayed : 0}

+
+ +
+ +

${step.text}

+ + + +
+ + +

+ + ${step.option1} +

+ +

+ + ${step.option2} +

+ + +
+
+ + +

${step.text}

+

+ Играть снова | + Начать сначала +

+
+
+ +
+ +
+

ID сессии: ${pageContext.session.id}

+

Текущий шаг: ${step.id}

+
+ + + + diff --git a/src/main/webapp/index.jsp b/src/main/webapp/index.jsp new file mode 100644 index 0000000..fd90c71 --- /dev/null +++ b/src/main/webapp/index.jsp @@ -0,0 +1,110 @@ +<%@ page contentType="text/html;charset=UTF-8" language="java" %> +<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %> + + + HelloQuest (||) начало + + + + + + +

Пролог

+ +
+Ты очнулся в космическом порту и голова покачивается на борту
+своего корабля. Разве ты не об этом мечтал? Стать капитаном
+галактического судна с экипажем, который будет совершать
+подвиги под твоим командованием.
+
+Так что вперёд!
+
+ +

Знакомство с экипажем

+ +
+Когда ты поднимаешься на борт корабля, тебя приветствует девушка
+с умной улыбкой в глазах:
+
+— Здравствуйте, командир! Я Зинаида — ваша помощница.
+Видите? Там в углу пьёт кофе наш штурман - сержант Перегарный Шлейф,
+    под штурвалом спит наш бортмеханик Чёрный Богдан,
+    а фоторрафирует его Сергей Стальная Пятка - наш навигатор.
+
+А как обращаться к вам?
+
+ +
+
+

+ +
+ + + diff --git a/src/main/webapp/result.jsp b/src/main/webapp/result.jsp new file mode 100644 index 0000000..d1e3da7 --- /dev/null +++ b/src/main/webapp/result.jsp @@ -0,0 +1,18 @@ +<%-- +<%@ page contentType="text/html;charset=UTF-8" language="java" %> +<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %> + + + Результат + + +

${sessionScope.result}

+Начать заново + +
+

Статистика сессии:

+

ID сессии: ${pageContext.session.id}

+

Время создания: ${pageContext.session.creationTime}

+ + +--%> \ No newline at end of file diff --git a/src/test/java/com/javarush/AppTest.java b/src/test/java/com/javarush/AppTest.java deleted file mode 100644 index 2fcbf44..0000000 --- a/src/test/java/com/javarush/AppTest.java +++ /dev/null @@ -1,38 +0,0 @@ -package com.javarush; - -import junit.framework.Test; -import junit.framework.TestCase; -import junit.framework.TestSuite; - -/** - * Unit test for simple App. - */ -public class AppTest - extends TestCase -{ - /** - * Create the test case - * - * @param testName name of the test case - */ - public AppTest( String testName ) - { - super( testName ); - } - - /** - * @return the suite of tests being tested - */ - public static Test suite() - { - return new TestSuite( AppTest.class ); - } - - /** - * Rigourous Test :-) - */ - public void testApp() - { - assertTrue( true ); - } -} diff --git a/src/test/java/com/javarush/quest/GameServletTest.java b/src/test/java/com/javarush/quest/GameServletTest.java new file mode 100644 index 0000000..c83f226 --- /dev/null +++ b/src/test/java/com/javarush/quest/GameServletTest.java @@ -0,0 +1,91 @@ +package com.javarush.quest; + +import com.javarush.quest.model.QuestStep; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; + +import javax.servlet.RequestDispatcher; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; +import javax.servlet.http.HttpSession; + +import static org.mockito.Mockito.*; + +class GameServletTest { + + private GameServlet servlet; + private HttpServletRequest request; + private HttpServletResponse response; + private HttpSession session; + private RequestDispatcher dispatcher; + + @BeforeEach + void setUp() { + servlet = new GameServlet(); + request = mock(HttpServletRequest.class); + response = mock(HttpServletResponse.class); + session = mock(HttpSession.class); + dispatcher = mock(RequestDispatcher.class); + + when(request.getSession()).thenReturn(session); + when(request.getContextPath()).thenReturn(""); + when(request.getRequestDispatcher("/game.jsp")).thenReturn(dispatcher); + } + + // ---------- doGet ---------- + + @Test + void doGet_withoutStep_shouldShowStart() throws Exception { + when(request.getParameter("step")).thenReturn(null); + + servlet.doGet(request, response); + + verify(request).setAttribute(eq("step"), any(QuestStep.class)); + verify(dispatcher).forward(request, response); + } + + @Test + void doGet_unknownStep_shouldReturn404() throws Exception { + when(request.getParameter("step")).thenReturn("unknown"); + + servlet.doGet(request, response); + + verify(response).sendError(eq(HttpServletResponse.SC_NOT_FOUND), anyString()); + } + + // ---------- doPost ---------- + + @Test + void doPost_invalidParams_redirectsToStart() throws Exception { + when(request.getParameter("answer")).thenReturn(null); + when(request.getParameter("currentStep")).thenReturn(null); + + servlet.doPost(request, response); + + verify(response).sendRedirect("/game?step=start"); + } + + @Test + void doPost_answer1_finalStep_incrementsGamesPlayed() throws Exception { + when(request.getParameter("answer")).thenReturn("1"); + when(request.getParameter("currentStep")).thenReturn("captain"); + when(session.getAttribute("gamesPlayed")).thenReturn(0); + + servlet.doPost(request, response); + + verify(session).setAttribute("gamesPlayed", 1); + verify(response).sendRedirect("/game?step=win"); + } + + @Test + void doPost_answer2_finalStep() throws Exception { + when(request.getParameter("answer")).thenReturn("2"); + when(request.getParameter("currentStep")).thenReturn("start"); + when(session.getAttribute("gamesPlayed")).thenReturn(null); + + servlet.doPost(request, response); + + verify(session).setAttribute("gamesPlayed", 1); + verify(response).sendRedirect("/game?step=lose1"); + } +} diff --git a/src/test/java/com/javarush/quest/StartServletTest.java b/src/test/java/com/javarush/quest/StartServletTest.java new file mode 100644 index 0000000..2f12937 --- /dev/null +++ b/src/test/java/com/javarush/quest/StartServletTest.java @@ -0,0 +1,62 @@ +package com.javarush.quest; + +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; + +import javax.servlet.RequestDispatcher; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; +import javax.servlet.http.HttpSession; + +import static org.mockito.Mockito.*; + +class StartServletTest { + + private StartServlet servlet; + private HttpServletRequest request; + private HttpServletResponse response; + private HttpSession session; + private RequestDispatcher dispatcher; + + @BeforeEach + void setUp() { + servlet = new StartServlet(); + request = mock(HttpServletRequest.class); + response = mock(HttpServletResponse.class); + session = mock(HttpSession.class); + dispatcher = mock(RequestDispatcher.class); + + when(request.getSession()).thenReturn(session); + when(request.getRequestDispatcher("/index.jsp")).thenReturn(dispatcher); + when(request.getContextPath()).thenReturn(""); + } + + @Test + void doGet_shouldForwardToIndexJsp() throws Exception { + servlet.doGet(request, response); + + verify(dispatcher).forward(request, response); + } + + @Test + void doPost_withPlayerName() throws Exception { + when(request.getParameter("playerName")).thenReturn("Roman"); + + servlet.doPost(request, response); + + verify(session).setAttribute("playerName", "Roman"); + verify(session).setAttribute("gamesPlayed", 0); + verify(response).sendRedirect("/game?step=start"); + } + + @Test + void doPost_withoutPlayerName_usesDefault() throws Exception { + when(request.getParameter("playerName")).thenReturn(" "); + + servlet.doPost(request, response); + + verify(session).setAttribute("playerName", "Искатель приключений"); + verify(session).setAttribute("gamesPlayed", 0); + verify(response).sendRedirect("/game?step=start"); + } +} diff --git a/src/test/java/com/javarush/quest/service/QuestServiceTest.java b/src/test/java/com/javarush/quest/service/QuestServiceTest.java new file mode 100644 index 0000000..fb01c08 --- /dev/null +++ b/src/test/java/com/javarush/quest/service/QuestServiceTest.java @@ -0,0 +1,73 @@ +package com.javarush.quest.service; +import com.javarush.quest.service.QuestService; +import com.javarush.quest.model.QuestStep; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.*; + +public class QuestServiceTest { + + private QuestService questService; + + @BeforeEach + void setUp() { + questService = new QuestService(); + } + + @Test + void shouldReturnStartStep() { + QuestStep start = questService.getStep("start"); + + assertNotNull(start); + assertEquals("start", start.getId()); + assertEquals("Принять вызов", start.getOption1()); + assertEquals("Отклонить вызов", start.getOption2()); + assertEquals("bridge", start.getNextStepId1()); + assertEquals("lose1", start.getNextStepId2()); + } + + @Test + void shouldReturnBridgeStep() { + QuestStep bridge = questService.getStep("bridge"); + + assertNotNull(bridge); + assertEquals("bridge", bridge.getId()); + assertEquals("captain", bridge.getNextStepId1()); + assertEquals("lose2", bridge.getNextStepId2()); + } + + @Test + void shouldReturnCaptainStep() { + QuestStep captain = questService.getStep("captain"); + + assertNotNull(captain); + assertEquals("captain", captain.getId()); + assertEquals("win", captain.getNextStepId1()); + assertEquals("lose3", captain.getNextStepId2()); + } + + @Test + void shouldDetectFinalWinStep() { + assertTrue(questService.isFinalStep("win")); + } + + @Test + void shouldDetectFinalLoseStep() { + assertTrue(questService.isFinalStep("lose1")); + assertTrue(questService.isFinalStep("lose2")); + assertTrue(questService.isFinalStep("lose3")); + } + + @Test + void shouldReturnNullForUnknownStep() { + QuestStep step = questService.getStep("unknown"); + + assertNull(step); + } + + @Test + void unknownStepIsNotFinal() { + assertFalse(questService.isFinalStep("unknown")); + } +} \ No newline at end of file