/*
 * Created on 2005. 5. 4.
 */
package net.javajigi.security.service;

import net.javajigi.security.dao.UserDAO;
import net.javajigi.security.model.User;

import org.easymock.MockControl;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import junit.framework.TestCase;

/**
 * @author Administrator
 */
public class SecurityServiceMockTest extends TestCase {
	private MockControl control = null;

	private UserDAO mock = null;

	private SecurityService service = null;

	private ApplicationContext ctx = null;

	/*
	 * @see TestCase#setUp()
	 */
	protected void setUp() throws Exception {
		control = MockControl.createControl(UserDAO.class); // 1
		mock = (UserDAO) control.getMock(); // 2

		String[] paths = { "/WEB-INF/applicationContext.xml" };
		ctx = new ClassPathXmlApplicationContext(paths);
		service = (SecurityService) ctx.getBean("securityService");
		service.setUserDAO(mock);
	}

	/*
	 * @see TestCase#tearDown()
	 */
	protected void tearDown() throws Exception {
		super.tearDown();
		service = null;
	}

	public void testAuthenticate() throws Exception {
		String userId = "javajigi";

		mock.findUser(userId);

		findUser(userId);

		boolean result = service.authenticate(userId, "password");

		assertEquals(true, result);
	}

	public void testAuthenticateFailedUserNotFound() throws Exception {
		mock.findUser("javajigi");
		
		control.setReturnValue(null);

        control.replay();

		try {
			boolean result = service.authenticate("javajigi", "password");
			fail("반환되는 User 객체의 값이 Null이여야 한다.");
		} catch (UserNotFoundException e) {
			e.printStackTrace();
			assertTrue(true);
		}
	}

	public void testAuthenticateFailedPasswordMisMatch() throws Exception {
		String userId = "javajigi";

		mock.findUser(userId);

		findUser(userId);

		try {
			boolean result = service.authenticate(userId, "pass");
		} catch (PasswordMisMatchException e) {
			e.printStackTrace();
			assertTrue(true);
		}
	}

	/**
	 * @param userId
	 */
	private void findUser(String userId) {
		User user = new User();
		user.setUserId(userId);
		user.setPassword("password");
		user.setName("박재성");
		user.setEmail("javajigi@gmail.com");

		control.setReturnValue(user);

		control.replay();
	}
}
