Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
768 views
in Technique[技术] by (71.8m points)

java - Junit difference between assertEquals(Double, Double) and assertEquals(double, double, delta)

I had a junit test asserting two Double objects with the following:

Assert.assertEquals(Double expected, Double result);

This was was fine then I decided to change it to use the primitive double instead which turned out to be deprecated unless you also provide a delta.

so what I am wondering is what is the difference between using the Double object or the primitive type in this assertEquals? Why is using the objects without a delta ok but then using the primitives without a delta is deprecated? Is Java doing something in the background which already has a default delta value taken into account?

Thanks.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

There is NO assert method in JUnit with the signature

assertEquals(Double expected, Double result);

There is one, however, generic for objects:

assertEquals(Object expected, Object result);

This calls the objects' equals method and as you can expect, it is not recommended to use this for comparing Double objects.

For doubles, as you observed, it is absolutely necessary to use a delta for comparison, to avoid issues with floating-point rounding (explained already in some other answers). If you use the 3-argument version of assertEquals with double arguments

assertEquals(double expected, double actual, double delta);

your Doubles will get silently unboxed to double and everything will work fine (and your tests won't fail unexpectedly :-).


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...