package io.ljunggren.csv.parser.mapper;

import static org.junit.Assert.assertEquals;

import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;

import org.junit.Test;

public class CatchAllMapperTest {

    int year;
    Long id;
    String text;
    NoStringCtor unsupported;

    @Test
    public void mapPrimitiveTest() throws Exception {
        Field field = this.getClass().getDeclaredField("year");
        Object object = new CatchAllMapper().map(field, "2021");
        assertEquals(2021, object);
    }

    @Test
    public void mapObjectTest() throws Exception {
        Field field = this.getClass().getDeclaredField("id");
        Object object = new CatchAllMapper().map(field, "1");
        assertEquals(1L, object);
    }

    @Test
    public void mapStringTest() throws Exception {
        Field field = this.getClass().getDeclaredField("text");
        Object object = new CatchAllMapper().map(field, "hello");
        assertEquals("hello", object);
    }

    @Test(expected = NoSuchMethodException.class)
    public void typeWithoutStringConstructorRaisesNoSuchMethod() throws Exception {
        Field field = this.getClass().getDeclaredField("unsupported");
        new CatchAllMapper().map(field, "x");
    }

    @Test(expected = InvocationTargetException.class)
    public void invalidNumericValueWrapsInvocationException() throws Exception {
        Field field = this.getClass().getDeclaredField("id");
        new CatchAllMapper().map(field, "not-a-number");
    }

    private static class NoStringCtor {
        @SuppressWarnings("unused")
        NoStringCtor(int notString) { }
    }

}
