package de.renew.formalism.function;

import java.lang.reflect.Field;

import org.junit.jupiter.api.Test;

import de.renew.unify.Impossible;
import de.renew.util.Value;

import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertThrows;

/**
 * @author 1huss
 */
class StaticFieldWriteFunctionTest {

    static public class DummyClass {
        public static int _intField;
        public static String _s;
    }

    @Test
    public void testFunctionGivenValue()
        throws NoSuchFieldException, Impossible, IllegalAccessException
    {
        //given
        Field field = DummyClass.class.getField("_intField");
        StaticFieldWriteFunction fieldWriteFunction = new StaticFieldWriteFunction(field);
        Value v = new Value(6);
        //when
        fieldWriteFunction.function(v);
        //then
        assertEquals(v.value, field.get(null));
    }

    @Test
    public void testFunctionGivenString() throws Exception {
        //given
        Field field = DummyClass.class.getField("_s");
        StaticFieldWriteFunction fieldWriteFunction = new StaticFieldWriteFunction(field);
        String s = "teststring";
        //when
        String result = (String) fieldWriteFunction.function(s);
        //then
        assertEquals(s, result);
        assertEquals(s, field.get(null));
    }

    @Test
    public void testFunctionThrowsIllegalTargetException() throws Exception {
        //given
        Field field = DummyClass.class.getField("_intField");
        StaticFieldWriteFunction fieldWriteFunction = new StaticFieldWriteFunction(field);
        Value v = new Value(1.1f);
        //when/then
        assertThrows(Impossible.class, () -> fieldWriteFunction.function(v));
    }

}