2

I wrote method that return random number between two given numbers. Here it's header:

int NumRange(int low,int high);

I want to check that method really return all the range between those two numbers, so I wrote a test (here below), but in my opinion it's too complicated. Maybe there is another way to check it, or I'm the best:)

TEST_F(RandomGeneratorTest, fill_all_the_range)
{
// In set - there is no duplicates
std::set<int> results;
int i;
for (i=0;i<1000;i++)
    results.insert(NumRange(0,9));
EXPECT_EQ(10, results.size());
}

Thank you, and sorry about my poor English.

EDIT: After question, I bring here below another test that I wrote to complete the test scenario.

TEST_F(RandomGeneratorTest, only_in_the_range)

{
int i,result;
for (i=0;i<1000;i++)
{
    result = NumRange(0,9);
    EXPECT_TRUE((result<=9) && (result>=0));
}
}

EDIT 2: Based on @cyborg answer (thank you), I made a histogram test (here below). But it's very complicated, and test, in my opinion, should be very simple, so my question still alive. I search simple way to check.

TEST_F(RandomGeneratorTest, fill_all_of_the_histogram_range)
{
int results[10]= {0};
int i, approxRes;
for (i=0;i<100000000;i++)
    results[NumRange(0,9)]+=1;
for (i=0;i<10;i++)
{
    approxRes = results[i]/10000;
    EXPECT_TRUE((approxRes<=1001) && (approxRes>=999));
}
}
yoni
  • 1,164
  • 2
  • 13
  • 29
  • What if your generator returns 0,1,2,3,4,5,6,7,8,9,9,9,9,9,9,9....? This fills the range but isn't really random. There are tests that check number sequences for randomness, such as [diehard tests](http://en.wikipedia.org/wiki/Diehard_tests). – n. m. could be an AI Dec 06 '11 at 08:02

1 Answers1

3

You could test for a uniform distribution instead of for a complete coverage. To do this, compute a histogram and check that every bin gets more or less the expected amount.

Edit:

If you want more serious tests, see this answer: https://stackoverflow.com/a/1477505/907578

Community
  • 1
  • 1
cyborg
  • 9,989
  • 4
  • 38
  • 56
  • The question is, What is the way to check a uniform distribution? – yoni Dec 06 '11 at 17:22
  • I told you how to validate that a distribution is uniform - create a histogram and check that all bins get approximately the expected value. – cyborg Dec 06 '11 at 18:10
  • I'm sorry, but my question was related google test or another unit test. How to write a test that check **histogram**. I understand the principle, but I can't check _approximately_ in test method. – yoni Dec 06 '11 at 18:23