I have to test that a method of my class return a value different from zero.my problem is that I don't know the assert I have to use.there is only assertEquals but not assertNotEquals.how can I do?
Asked
Active
Viewed 310 times
0
-
4http://stackoverflow.com/questions/1096650/why-doesnt-junit-provide-assertnotequals-methods – Petar Minchev Jul 13 '12 at 08:34
-
I'm using junit 4.10 and when I try to use assertThat it show me that is or not aren't found.I had imported org.harmcrest.where is the mistake? – Mazzy Jul 13 '12 at 08:48
-
@Mazzy - FYI, you should 1) Cut/paste the exact error message, 2) post your code, 3) specify your JUnit version. This helps *enormously* in giving you an accurate answer. IMHO... – paulsm4 Jul 13 '12 at 19:41
4 Answers
0
Use
Assert.assertTrue(actualValue!=0);
but this do not give you the informative message in case of failure

Viktor Stolbin
- 2,899
- 4
- 32
- 53
-
This is my number one complaint with JUnit. Why is there no assertNotEquals? – Thilo Jul 13 '12 at 08:36
-
1Because with the equals test you are stating that there is a single expected value that the test value should match. With a notEquals test there is not a single value that the test value can take, so there's no way to report "Expected test value to be x, but got y." So you may as well use assertTrue because there's no need for an expected value to be provided to the test method. – Bobulous Jul 14 '12 at 11:57
0
I think you use JUnit3(or higher) and you want to test if an int i != 0
. You should use:
import junit.framework.TestCase;
public class Tests extends TestCase {
public void testMe(){
int i = 4;
assertNotSame("msg on fail", i, 0);
}
}
use assertNotSame
for testing unequal.
Use assertNotNull
for o != null

Simulant
- 19,190
- 8
- 63
- 98
-
1Do not use assertNotSame to test primitive values. In JUnit the assertSame and assertNotSame tests are used to test whether two object references (variables) point to exactly the same object in memory. If you use it with primitive values, Java will autobox the primitive values into new Number objects (like Integer and Long) and they will likely be different, so assertNotSame will always succeed even if the numeric values are the same. – Bobulous Jul 14 '12 at 11:55
-
when i run the following test it fails, so i think your last point cannot be right all the way. But i see that there might be sometimes problemes. `public void testMe(){ int i = 4; assertNotSame("msg on fail", i, 4); }` – Simulant Jul 14 '12 at 21:21
0
Hamcrest is your friend here. Use
assertThat(currentValue, not(equalTo(0)))
This is readable and produces a decent message in case of failure.

Kkkev
- 4,716
- 5
- 27
- 43