/**
 * JOnAS: Java(TM) Open Application Server
 * Copyright (C) 2012 Bull S.A.S.
 * Contact: jonas-team@ow2.org
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA
 *
 * --------------------------------------------------------------------------
 * $Id: $
 * --------------------------------------------------------------------------
 */


package org.ow2.jonas.jndi.interceptors.impl.datasource;

import java.lang.reflect.Method;

import javax.naming.Context;
import javax.sql.DataSource;

import org.mockito.Mock;
import org.mockito.MockitoAnnotations;
import org.ow2.carol.jndi.intercept.InterceptionContext;
import org.ow2.jonas.jndi.checker.api.IResourceCheckerManager;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Test;

import static org.mockito.Mockito.when;
import static org.testng.Assert.assertEquals;

/**
 * A {@code DataSourceLeakDetectorContextInterceptorTestCase} is ...
 *
 * @author Guillaume Sauthier
 */
public class DataSourceLeakDetectorContextInterceptorTestCase {

    @Mock
    private IResourceCheckerManager manager;

    @Mock
    private InterceptionContext context;

    @Mock
    private DataSource dataSource;

    @BeforeMethod
    public void setUp() throws Exception {
        MockitoAnnotations.initMocks(this);
    }

    @Test
    public void testDataSourceWrapping() throws Exception {

        when(context.proceed()).thenReturn(dataSource);
        when(context.getMethod()).thenReturn(method(Context.class, "lookup", String.class));
        when(context.getParameters()).thenReturn(new Object[] {"unused-jndi-name"});

        DataSourceLeakDetectorContextInterceptor interceptor = new DataSourceLeakDetectorContextInterceptor();
        interceptor.setResourceCheckerManager(manager);

        Object o = interceptor.intercept(context);
        assertEquals(o.getClass(), DatasourceWrapper.class);
    }

    private static Method method(Class<?> type, String method, Class<?>... types) {
        try {
            return type.getMethod(method, types);
        } catch (NoSuchMethodException e) {
            throw new IllegalStateException("Cannot get method on type", e);
        }
    }

}
