Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In a Java unit test, how do I assert a number is within a given range?

Tags:

Coming to Java from Python. I recognize this is pretty basic, but it doesn't seem this has been asked here yet and Google is being coy with me.

In Python, I'd simply do something like this but Java objects:

assertTrue(min <= mynum and mynum <= max); 
like image 625
klenwell Avatar asked Mar 15 '12 01:03

klenwell


People also ask

What does the assert () method do in unit testing?

The assertSame() and assertNotSame() methods tests if two object references point to the same object or not. It is not enough that the two objects pointed to are equals according to their equals() methods. It must be exactly the same object pointed to. The calls to myUnit.

How do you assert two values in Java?

We can use the equals() method to compare two integers in Java. It returns true if both objects are equal; otherwise, it returns false.

What does assert equals do in Java?

assertEquals. public static void assertEquals(Object expected, Object actual) Asserts that two objects are equal. If they are not, an AssertionError without a message is thrown. If expected and actual are null , they are considered equal.


1 Answers

I'd write:

assertTrue("mynum is out of range: " + mynum, min <= mynum && mynum <= max); 

but technically you just need:

assertTrue(min <= mynum && mynum <= max); 

Either way, be sure to write && and not and.

like image 75
ruakh Avatar answered Sep 28 '22 07:09

ruakh