klenwell
klenwell

Reputation: 7148

In Java unit tests, is it possible to include an assert statement within a loop?

Here's my test:

@Test
public void randomDouble() {
    int Min = -1;
    int Max = 1;
    double r;

    for (int i = 0; i < 5; i++) {
        r = Min + (Math.random() * ((Max - Min) + 1));
        System.out.printf("%d %d: %.1f\n", Min, Max, r);
        assertTrue(Max < r && Max > r);
    }
}

It seems that the test returns after the first time the assertTrue statement within the loop is run. If I remove it, I get 5 results output. With it, I get only one.

I use this pattern in Python for fuzz testing.

Upvotes: 0

Views: 2657

Answers (3)

andrew cooke
andrew cooke

Reputation: 46872

there's nothing to restrict asserts from being in loops.

some other points, though:

  • the test will always fail (see next item for what you probably want)

  • java has an assert in the language: assert Min <= r && r <= Max : "bad range"

  • the "+1" in ((Max - Min) + 1) seems wrong to me

Upvotes: 3

David Gelhar
David Gelhar

Reputation: 27900

Even if you change the assertion to assertTrue(Min < r && Max > r);, which seems to be what is intended, the test still frequently fails on the first iteration: the "+1" in r = Min + (Math.random() * ((Max - Min)+1)); is wrong.

Upvotes: 1

Oliver Charlesworth
Oliver Charlesworth

Reputation: 272717

The assertion fails on the first iteration; it can never pass (how can r be both bigger and smaller than Max?).

Upvotes: 5

Related Questions