Created
November 27, 2018 14:21
-
-
Save robshep/1f1c2e0fdf88039ea09113954da71be1 to your computer and use it in GitHub Desktop.
Testing Java against Javascript implemenations
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import static org.assertj.core.api.Assertions.assertThat; | |
import java.io.InputStreamReader; | |
import java.util.Random; | |
import javax.script.ScriptEngine; | |
import javax.script.ScriptEngineManager; | |
import javax.script.ScriptException; | |
import org.junit.Test; | |
import lombok.extern.slf4j.Slf4j; | |
@Slf4j | |
public class HoursRoundingTests { | |
@Test | |
public void test2DPRounding() throws ScriptException | |
{ | |
ScriptEngine engine = new ScriptEngineManager().getEngineByName("nashorn"); | |
engine.eval(new InputStreamReader(HoursRoundingTests.class.getResourceAsStream("/lodash.js"))); | |
Object object = engine.eval("_.VERSION"); | |
assertThat(object.getClass()).isEqualTo(String.class); | |
assertThat(object.toString()).isEqualTo("4.17.11"); | |
log.warn("{} - {}", object.getClass(), object.toString()); | |
Random rand = new Random(); | |
for(int i=0;i<1000;i++){ | |
double nextDouble = rand.nextDouble(); | |
int nextInt = rand.nextInt(1000); | |
double toTest = nextInt * nextDouble; | |
double javaRounded = IncidentService.roundTo2dp(toTest); | |
Double lodashRounded = (Double) engine.eval(String.format("_.round(%f, 2)", toTest)); | |
log.info("Round: {} - java:[{}] - lodash:[{}]", toTest, javaRounded, lodashRounded); | |
assertThat(lodashRounded).isEqualTo(javaRounded).as("Round: %f - java:[%f] - lodash:[%f]", toTest, javaRounded, lodashRounded); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment