Форум программистов, компьютерный форум CyberForum.ru

С++ для начинающих

Войти
Регистрация
Восстановить пароль
 
QWERY_2012
5 / 5 / 2
Регистрация: 09.09.2012
Сообщений: 227
#1

Как написать тест программ для след класса - C++

21.10.2012, 04:13. Просмотров 759. Ответов 0
Метки нет (Все метки)

Задача написать тест программу кот выполняет проверку Student class:

The three-argument Student class constructor
The enroll member function.

C++
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
#ifndef STUDENT_H
#define STUDENT_H
#include <string>
using namespace std;
 
class Student
{
public:
    Student();
    Student(string thisStudentID);
    void enroll(string thisSectionID);
private:
    string studentID;
    bool timeToThrow();
    static int sneakyCount;
};
#endif
C++
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
#include <string>
#include <iostream>
#include "Student.h"
#include "StudentException.h"
using namespace std;
 
// The constructor for this class accepts a Student ID
Student::Student(string thisStudentID)
{
    // This first statement updates a variable used to help decide when to Throw an Exception
    sneakyCount++;
    // Any text will be accepted as the student ID in this implementation
    if (!timeToThrow())
        studentID = thisStudentID;
    else
        throw StudentException("Student " + thisStudentID + " has been expelled from this school");
}
// This default constructor shouldn't be used, so throwing an exception isn't so artificial, its
// the right thing to do.  We will also find out if this constructor gets called at time that we don't expect.
Student::Student()
{
    // This first statement updates a variable used to help decide when to Throw an Exception
    sneakyCount++;
    throw StudentException("Incorrect Call to Student Constructor - No Student ID Provided");
}
// This dummy function would enroll the student in a course
void Student::enroll(string thisSectionID)
{
    // This first statement updates a variable used to help decide when to Throw an Exception
    sneakyCount++;
    if (!timeToThrow())
        cout << endl << "Student: " << studentID << " is now enrolled in " << thisSectionID << endl;
    else
        throw StudentException("Section " + thisSectionID + " has been cancelled");
    return;
}
// This is the code that helps decide when to throw an exception.  You are welcome to look at it,
// but its only here to help generate unexpected exceptions.  It will vary in different versions of Student
// as I play around with it. 
int Student::sneakyCount = 0;
 
bool Student::timeToThrow()
{
    if (sneakyCount == 4)
        return true;
    else
        return false;
}

C++
1
2
3
4
5
6
7
8
9
10
11
12
13
14
#ifndef STUDENTEXCEPTION_H
#define STUDENTEXCEPTION_H
#include <string>
using namespace std;
 
class StudentException
{
public:
    StudentException(string thisErrorMessage);
    string errorMessage();
private:
    string message;
};
#endif
C++
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
#include <string>
#include "StudentException.h"
using namespace std;
 
StudentException::StudentException(string whatWentWrong)
{
    // Set the stored message within the object
    // Any text will be accepted as the error message
    message = whatWentWrong;
}
// Return the error message stored inside the object
string StudentException::errorMessage()
{
    return message;
}

Дословно задача звучит так:
Problem 1: Catching Exceptions of an Externally Provided Class

This problem simulates having to handle the exceptions of an externally provided class. (It also gives us one more opportunity to practice using classes in separately compilable files.) The problem is to write a test program that exercises a class that supports exceptions. The links above provide header and implementation files for two classes:

A Student class that simulates a class we might write to support the processing of students at FRCC.
A StudentException class that is used by the Student class to throw useful exceptions.
Your task is to download these class files and write a simple test program that exercises the following Student class features:

The three-argument Student class constructor
The enroll member function
Your program should correctly handle any exceptions that get thrown by the use of those functions and should display a useful error message. You can determinate how to use the Student class and StudentException class member functions from the comments in their header files. Please don't do any prompting for values in your program, simply call the member functions with fixed values, something like:

Student thisStudent("S12345678");
thisStudent.enroll("CSC-160-500");

Create at least three Student objects and "enroll" each of those students in a course. The provided class file will generate an exception on at least one of those calls. Your code should be written to handle exceptions as follows:

You should Catch any exceptions of type StudentException and use the member functions of the StudentException class to display a useful message to the user.
You should also Catch all other exceptions that might be thrown (we have a way of catching all) and print out a generic error message for those.
Here's a minimal example of the code your test program will execute:

// Declare student objects and enroll those students in sections
Student testStudent1("S0000001"), testStudent2("S0000002"),testStudent3("S0000003");
testStudent1.enroll("CSC-160-500");
testStudent2.enroll("CSC-161-500");
testStudent3.enroll("PHI-112-500");
Your test program will need to run code much like this and catch any exceptions that get thrown by calls to Student class member functions.

I will create multiple versions of the Student class, other than the one provided, that generate exceptions in different ways, including some exceptions that aren't of type StudentException. Your test program should run correctly with any of them and should Catch exceptions no matter which Student member functions throw them. I might grade your homework using any or all of these alternate Student class implementations.
Similar
Эксперт
41792 / 34177 / 6122
Регистрация: 12.04.2006
Сообщений: 57,940
21.10.2012, 04:13     Как написать тест программ для след класса
Посмотрите здесь:

C++ При перегрузке оператора для класса не получается использовать имя переменной такое же, как в описании класса
C++ тест программы (класса)!
Как написать модульный тест для функции main C++
Как для класса написать перегруженный оператор new? C++
C++ Как написать конструктор для класса, в котором содержится структура?
C++ Написать перегрузку для класса Fraction и double
C++ Тест для класса
C++ Написать элементарный медиа-центр для запуска программ
Написать код программы для реализации класса human C++
Написать деструктор для данного класса C++
C++ Написать для класса деструктор, выводящий надпись
Написать функцию для класса, возращающую данный из вектора обьектов класса по итератору вектора C++

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

Или воспользуйтесь поиском по форуму:
После регистрации реклама в сообщениях будет скрыта и будут доступны все возможности форума.
Ответ Создать тему
Опции темы

Текущее время: 14:48. Часовой пояс GMT +3.
КиберФорум - форум программистов, компьютерный форум, программирование
Powered by vBulletin® Version 3.8.9
Copyright ©2000 - 2017, vBulletin Solutions, Inc.
Рейтинг@Mail.ru