Форум программистов, компьютерный форум, киберфорум
Java SE (J2SE)
Войти
Регистрация
Восстановить пароль
Блоги Сообщество Поиск Заказать работу  
 
Рейтинг 4.73/11: Рейтинг темы: голосов - 11, средняя оценка - 4.73
0 / 0 / 1
Регистрация: 02.06.2018
Сообщений: 6

Задача, модульное тестирование

12.07.2018, 18:29. Показов 2233. Ответов 6
Метки test (Все метки)

Студворк — интернет-сервис помощи студентам
Помогите с задачей.
Методы класса TextAnalyzer покрыть тестами (модульное тестирование). Должно быть 5 тестов (2 правильных и 3 исключения).

Java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
import java.nio.file.Files;
import java.nio.file.Paths;
 
public class Loader
{
    public static void main(String[] args) throws Exception
    {
        //Reading file to the String
        String text = new String(Files.readAllBytes(Paths.get("res/text_01.txt")));
 
        TextAnalyzer analyzer = new TextAnalyzer(text);
        System.out.println("Most frequent word: " + analyzer.getMostFrequentWord());
    }
}
Java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
import java.util.*;
 
public class TextAnalyzer
{
    private String text;
 
    public TextAnalyzer(String text)
    {
        this.text = text;
    }
 
    /**
     * Splits the text into words
     * @return
     */
    public ArrayList<String> getWords()
    {
        String fragments[] = splitTextIntoFragments();
        ArrayList<String> words = new ArrayList<>();
        for(String fragment : fragments)
        {
            if (fragment.matches(".*[a-zA-Z].*")) {
                words.add(fragment);
            }
        }
        return words;
    }
 
    public String getMostFrequentWord()
    {
        ArrayList<String> words = getWords();
        TreeMap<String, Integer> wordCounts = new TreeMap<>();
        for(String word : words)
        {
            Integer count = wordCounts.get(word);
            wordCounts.put(word, count == null ? 1 : count + 1);
        }
        Collections.sort(words, new Comparator<String>() {
            @Override
            public int compare(String o1, String o2) {
                return wordCounts.get(o2) - wordCounts.get(o1);
            }
        });
        return words.get(0);
    }
 
    //========================================================
 
    private String[] splitTextIntoFragments()
    {
        return text.toLowerCase().split("[^a-z0-9\\-']");
    }
}

Текст из файла: text_01.txt

Japan has restarted its first nuclear reactor under new safety rules following the 2011 Fukushima disaster.
All Japan's nuclear plants were gradually shut down after a series of meltdowns at the Fukushima plant sparked by the tsunami and earthquake.
But after passing stringent new safety tests, Kyushu Electric Power restarted the number one reactor at its Sendai plant on Tuesday morning.
There is still strong public unease about a return to nuclear power.
Protests have been taking place outside the Sendai plant and at Prime Minister Shinzo Abe's residence in Tokyo, about 1,000 km (600 miles) away.
The BBC's Rupert Wingfield-Hayes in Tokyo says that after being told a disaster like Fukushima could never happen, public confidence has been shaken.
A total of 25 plants have applied to be restarted, he says, but all are facing legal challenges from concerned locals.
'Safety first'
Kyushu said reactor No.1 at Sendai began operating again at 10:30 local time (01:30 GMT).
Reactors 1 and 2 at Sendai nuclear plant, Japan (7 July Aug)
The plant is expected to be producing energy by the end of the week
TV images showed the plant's control room as workers turned the reactor back on.
Kyushu Electric spokesman Tomomitsu Sakata said the reactor had gone back online without any problems.
It will be about 24 hours before a full reaction takes place, and the plant is expected to start generating power by Friday. It will reach full capacity some time next month.
Prime Minister Abe said on Monday that the reactors had passed "the world's toughest safety screening".
"I would like Kyushu Electric to put safety first and take utmost precautions for the restart," he said.
Protesters outside Sendai plant. 10 Aug 2015
Many local residents are unhappy about the Sendai plant restarting
Since shutting down all nuclear plants, Japan has been relying on imported fossil fuels for its energy, at huge expense. The government has said nuclear power must resume to cut both import bills and growing CO2 emissions.
Experts have also warned that reactors left idle for years tend to experience teething problems and that such a mass restart of dormant reactors has never been attempted before, says our correspondent.
Japan's Nuclear Regulation Authority approved two reactors at the Sendai plant last September under stricter safety rules. The second reactor is due to be restarted in October.
More than $100m (?64m) has been spent on fitting new safety systems at the Sendai plant.
Scene after explosion at the Fukushima Daiichi plant. March 2011
The Fukushima Daiichi plant was badly damaged by the earthquake and tsunami
But local residents say the new safety regulations are not stringent enough - they are worried about potential dangers from active volcanoes in the region.
Protesters were rallied by Naoto Kan, prime minister at the time of the Fukushima crisis, who told the crowd: "We don't need nuclear plants."
He said the Fukushima disaster had "exposed the myth of safe and cheap nuclear power, which turned out to be dangerous and expensive".
Jump media playerMedia player helpOut of media player. Press enter to return or tab to continue.
Media caption
The robot has produced the first video from inside the reactor, as Rupert Wingfield-Hayes reports
One of the most powerful earthquakes ever recorded struck off the coast of Japan in March 2011, triggering a huge tsunami which damaged the Fukushima nuclear plant, leading to meltdown.
Almost 16,000 people died and more than 2,500 are still listed as missing, though none of the deaths has been linked to the nuclear disaster.
Some 160,000 people were evacuated from the surrounding areas in the following weeks - continuing high radiation levels mean most have never been able to return home.
0
Лучшие ответы (1)
Programming
Эксперт
39485 / 9562 / 3019
Регистрация: 12.04.2006
Сообщений: 41,671
Блог
12.07.2018, 18:29
Ответы с готовыми решениями:

Модульное тестирование метода со Scaner и PrintWriter
Подскажите, пожалуйста, как написать тест для метода который считывает данные с клавиатуры и выводит на экран?

Тести́рование програ́ммного обеспе́чения(Модульное тестирование, или юнит-тестирование)
Извиняюсь перед администрацией что разместил тему в несоответствующем разделе, не мог найти про тестирование ПО. На днях встал вопрос о...

Модульное тестирование
Здравствуйте! Решил посмотреть, что же такое эти юнит-тесты. Написал простенький метод сложения двух чисел private int GetNum(int a,...

6
Автоматизируй это!
Эксперт Python
 Аватар для Welemir1
7390 / 4817 / 1246
Регистрация: 30.03.2015
Сообщений: 13,667
Записей в блоге: 29
12.07.2018, 18:41
Hektor12, а с чем помочь то?
не понял зачем тут текст такой большой, достаточно короткой строки из букв, разделенных пробелами. Сами методы по идее должны бросать исключения или уж возвращать пустой аррейлист, пустую строку в случае проблем

1) создаем новый класс, импортируем тестовый фреймворк (я бы взял тестНГ, но можно и жЮнит)
2) первый позитивный тест передаем текст "a b c a d", вызываем метод getWords() и убеждаемся (assert) что в нем 5 слов
3) второй позитивный тест, передаем текст "a b c a d", вызываем метод getMostFrequentWord(), убеждаемся что ответ равен a
4) негативный тест, передаем пустую строку "", ассертим падение исключения
5) негативный тест, передаем пробел " ", ассертим исключение
6) негативный тест, передаем символы "--", ассертим исключение
1
0 / 0 / 1
Регистрация: 02.06.2018
Сообщений: 6
12.07.2018, 19:22  [ТС]
2 позитивных я сделал, можете показать 1 негативный в виде кода?
Java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
import org.junit.Assert;
import org.junit.Test;
 
public class TextAnalyzerTest
{
    TextAnalyzer textAnalyzer = new TextAnalyzer("a b c a d");
 
    @Test
    public void getWords()
    {
        String actual[] = textAnalyzer.getWords().toArray(new String[0]);
        String excepted[] = {"a", "b", "c", "a", "d"};
        Assert.assertArrayEquals(excepted, actual);
    }
 
    @Test
    public void getMostFrequentWord()
    {
        String excepted = "a";
        Assert.assertEquals(excepted , textAnalyzer.getMostFrequentWord());
    }
}
0
Эксперт Java
3639 / 2971 / 918
Регистрация: 05.07.2013
Сообщений: 14,220
12.07.2018, 19:28
@ExceptionThrown или что-то в таком духе над тестом, в тесте соответственно вызываешь свой метод с кривыми аргументами

Добавлено через 58 секунд
@Test(expected = IndexOutOfBoundsException.class)
1
0 / 0 / 1
Регистрация: 02.06.2018
Сообщений: 6
12.07.2018, 19:31  [ТС]
Так?
Java
1
2
3
4
5
6
@Test (expected = org.junit.ComparisonFailure.class)
    public void getMostFrequentWord2()
    {
        String excepted = "";
        Assert.assertEquals(excepted,textAnalyzer.getMostFrequentWord());
    }
0
Автоматизируй это!
Эксперт Python
 Аватар для Welemir1
7390 / 4817 / 1246
Регистрация: 30.03.2015
Сообщений: 13,667
Записей в блоге: 29
12.07.2018, 19:31
Лучший ответ Сообщение было отмечено Hektor12 как решение

Решение

Hektor12, жЮнит4
Java
1
2
3
4
@Test(expected = IndexOutOfBoundsException.class)
    public void shouldThrowIfEmptyText() {
        new TextAnalyzer("").getMostFrequentWord();
    }
1
0 / 0 / 1
Регистрация: 02.06.2018
Сообщений: 6
12.07.2018, 19:36  [ТС]
Спасибо, разобрался.
0
Надоела реклама? Зарегистрируйтесь и она исчезнет полностью.
inter-admin
Эксперт
29715 / 6470 / 2152
Регистрация: 06.03.2009
Сообщений: 28,500
Блог
12.07.2018, 19:36
Помогаю со студенческими работами здесь

Модульное тестирование
недавно понял, что сложно делать программу без тестирования её модулей. При изменении кода через большое время может вылазить ошибка, и на...

Модульное тестирование
Изучаю модульное тестирование. Для практики решил реализовать очередь, которую решено было тестировать. Получилось вот что: import...

Модульное тестирование c++
Здравствуйте. Подскажите, пожалуйста, документацию или пример по написанию таких тестов. Сам нагуглил только сторонние библиотеки для...

Модульное тестирование
Задание в том, что я создаю тест кейс, который тестирует работу программы. Нужно проверить за счет работы кнопки правильно ли он считает...

Модульное тестирование, Assert
Всем привет, есть вопрос! В модульном тесте у меня идет подряд множество Assert-ов: Assert.AreEqual(p1,p2, message); //..; ...


Искать еще темы с ответами

Или воспользуйтесь поиском по форуму:
7
Ответ Создать тему
Новые блоги и статьи
http://iceja.net/ математические сервисы
iceja 20.01.2026
Обновила свой сайт http:/ / iceja. net/ , приделала Fast Fourier Transform экстраполяцию сигналов. Однако предсказывает далеко не каждый сигнал (см ограничения http:/ / iceja. net/ fourier/ docs ). Также. . .
http://iceja.net/ сервер решения полиномов
iceja 18.01.2026
Выкатила http:/ / iceja. net/ сервер решения полиномов (находит действительные корни полиномов методом Штурма). На сайте документация по API, но скажу прямо VPS слабенький и 200 000 полиномов. . .
Расчёт переходных процессов в цепи постоянного тока
igorrr37 16.01.2026
/ * Дана цепь постоянного тока с R, L, C, k(ключ), U, E, J. Программа составляет систему уравнений по 1 и 2 законам Кирхгофа, решает её и находит: токи, напряжения и их 1 и 2 производные при t = 0;. . .
Восстановить юзерскрипты Greasemonkey из бэкапа браузера
damix 15.01.2026
Если восстановить из бэкапа профиль Firefox после переустановки винды, то список юзерскриптов в Greasemonkey будет пустым. Но восстановить их можно так. Для этого понадобится консольная утилита. . .
Сукцессия микоризы: основная теория в виде двух уравнений.
anaschu 11.01.2026
https:/ / rutube. ru/ video/ 7a537f578d808e67a3c6fd818a44a5c4/
WordPad для Windows 11
Jel 10.01.2026
WordPad для Windows 11 — это приложение, которое восстанавливает классический текстовый редактор WordPad в операционной системе Windows 11. После того как Microsoft исключила WordPad из. . .
Classic Notepad for Windows 11
Jel 10.01.2026
Old Classic Notepad for Windows 11 Приложение для Windows 11, позволяющее пользователям вернуть классическую версию текстового редактора «Блокнот» из Windows 10. Программа предоставляет более. . .
Почему дизайн решает?
Neotwalker 09.01.2026
В современном мире, где конкуренция за внимание потребителя достигла пика, дизайн становится мощным инструментом для успеха бренда. Это не просто красивый внешний вид продукта или сайта — это. . .
КиберФорум - форум программистов, компьютерный форум, программирование
Powered by vBulletin
Copyright ©2000 - 2026, CyberForum.ru