]>
Commit | Line | Data |
---|---|---|
7c673cae FG |
1 | // (C) Copyright 2015 Boost.Test team. |
2 | // Distributed under the Boost Software License, Version 1.0. | |
3 | // (See accompanying file LICENSE_1_0.txt or copy at | |
4 | // http://www.boost.org/LICENSE_1_0.txt) | |
5 | ||
6 | // See http://www.boost.org/libs/test for the library home page. | |
7 | ||
8 | //[example_code | |
9 | #define BOOST_TEST_MODULE example | |
10 | #include <boost/test/included/unit_test.hpp> | |
11 | #include <stdexcept> | |
12 | #include <fstream> | |
13 | ||
14 | //! Computes the histogram of the words in a text file | |
15 | class FileWordHistogram | |
16 | { | |
17 | public: | |
18 | //!@throw std::exception if the file does not exist | |
19 | FileWordHistogram(std::string filename) : is_processed(false), fileStream_(filename) { | |
20 | if(!fileStream_.is_open()) throw std::runtime_error("Cannot open the file"); | |
21 | } | |
22 | ||
23 | //! @returns true on success, false otherwise | |
24 | bool process() { | |
25 | if(!is_processed) return true; | |
26 | ||
27 | // ... | |
28 | is_processed = true; | |
29 | return true; | |
30 | } | |
31 | ||
32 | //!@pre process has been called with status success | |
33 | //!@throw std::logic_error if preconditions not met | |
34 | std::map<std::string, std::size_t> | |
35 | result() const { | |
36 | if(!is_processed) | |
37 | throw std::runtime_error("\"process\" has not been called or was not successful"); | |
38 | return histogram; | |
39 | } | |
40 | ||
41 | private: | |
42 | bool is_processed; | |
43 | std::ifstream fileStream_; | |
44 | std::map<std::string, std::size_t> histogram; | |
45 | }; | |
46 | ||
47 | BOOST_AUTO_TEST_CASE( test_throw_behaviour ) | |
48 | { | |
49 | // __FILE__ is accessible, no exception expected | |
50 | BOOST_REQUIRE_NO_THROW( FileWordHistogram(__FILE__) ); | |
51 | ||
52 | // ".. __FILE__" does not exist, API says std::exception, and implementation | |
53 | // raises std::runtime_error child of std::exception | |
54 | BOOST_CHECK_THROW( FileWordHistogram(".." __FILE__), std::exception ); | |
55 | ||
56 | { | |
57 | FileWordHistogram instance(__FILE__); | |
58 | ||
59 | // api says "std::logic_error", implementation is wrong. | |
60 | // std::runtime_error not a child of std::logic_error, not intercepted | |
61 | // here. | |
62 | BOOST_CHECK_THROW(instance.result(), std::logic_error); | |
63 | } | |
64 | } | |
65 | //] |