/* * Copyright (c) 2010 Mysema Ltd. * All rights reserved. * */ package com.mysema.codegen; import static org.junit.Assert.*; import java.io.IOException; import java.net.URLClassLoader; import java.util.Arrays; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; import org.junit.Assert; import org.junit.Before; import org.junit.Test; public class EvaluatorFactoryTest { public static class TestEntity { private final String name; public TestEntity(String name){ this.name = name; } public String getName() { return name; } } private EvaluatorFactory factory; private List names = Arrays.asList("a","b"); private List> ints = Arrays.>asList(int.class, int.class); private List> strings = Arrays.>asList(String.class, String.class); private List> string_int = Arrays.>asList(String.class, int.class); @Before public void setUp() throws IOException{ factory = new EvaluatorFactory((URLClassLoader) getClass().getClassLoader()); } @Test public void testSimple(){ for (String expr : Arrays.asList("a.equals(b)", "a.startsWith(b)", "a.equalsIgnoreCase(b)")){ evaluate(expr, boolean.class, names, strings, Arrays.asList("a","b"), Collections.emptyMap()); } for (String expr : Arrays.asList("a != b", "a < b", "a > b", "a <= b", "a >= b")){ evaluate(expr, boolean.class, names, ints, Arrays.asList(0,1), Collections.emptyMap()); } } @Test public void testResults(){ // String + String test("a + b", String.class, names, strings, Arrays.asList("Hello ", "World"), "Hello World"); // String + int test("a.substring(b)", String.class, names, string_int, Arrays.asList("Hello World", 6), "World"); // int + int test("a + b", int.class, names, ints, Arrays.asList(1,2), 3); } @Test public void testWithConstants(){ Map constants = new HashMap(); constants.put("x", "Hello World"); List> types = Arrays.>asList(String.class); List names = Arrays.asList("a"); assertEquals(Boolean.TRUE, evaluate("a.equals(x)", boolean.class, names, types, Arrays.asList("Hello World"), constants)); assertEquals(Boolean.FALSE, evaluate("a.equals(x)", boolean.class, names, types, Arrays.asList("Hello"), constants)); } @Test public void testCustomType(){ test("a.getName()", String.class, Collections.singletonList("a"), Collections.>singletonList(TestEntity.class), Arrays.asList(new TestEntity("Hello World")), "Hello World"); } private void test(String source, Class projectionType, List names, List> types, List args, Object expectedResult){ Assert.assertEquals(expectedResult, evaluate(source, projectionType, names, types, args, Collections.emptyMap())); } private Object evaluate(String source, Class projectionType, List names, List> types, List args, Map constants) { Evaluator evaluator = factory.createEvaluator( source, projectionType, names.toArray(new String[names.size()]), types.toArray(new Class[types.size()]), constants); return evaluator.evaluate(args.toArray()); } }