/*
 * Copyright 2018 Scytl Secure Electronic Voting SA
 *
 * All rights reserved
 *
 * See our extended copyright notice in *file 'Copyright.txt' which is part of this source code package
 */
package com.scytl.products.ov.ei.services.infrastructure.persistence;

import static org.junit.Assert.assertNotNull;
import static org.mockito.Matchers.eq;
import static org.mockito.Mockito.when;

import javax.persistence.NoResultException;
import javax.persistence.TypedQuery;

import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.InjectMocks;
import org.mockito.Matchers;
import org.mockito.Mock;
import org.mockito.runners.MockitoJUnitRunner;

import com.scytl.products.ov.commons.beans.exceptions.ResourceNotFoundException;
import com.scytl.products.ov.commons.infrastructure.persistence.BaseRepositoryImplTest;
import com.scytl.products.ov.ei.services.domain.model.ballot.Ballot;
import com.scytl.products.ov.ei.services.domain.model.ballot.BallotRepository;

/**
 * Junit tests for the class {@link BallotRepositoryImpl}.
 */
@RunWith(MockitoJUnitRunner.class)
public class BallotRepositoryImplTest extends BaseRepositoryImplTest<Ballot, Integer> {

	@Mock
	private TypedQuery<Ballot> queryMock;

	@InjectMocks
	private static BallotRepository ballotRepository = new BallotRepositoryImpl();

	/**
	 * Creates a new object of the testing class.
	 */
	public BallotRepositoryImplTest() throws InstantiationException, IllegalAccessException {
		super(Ballot.class, ballotRepository.getClass());
	}

	@Before
	public void setup() {
		when(entityManagerMock.createQuery(Matchers.anyString(), eq(Ballot.class))).thenReturn(queryMock);
		when(queryMock.setParameter(Matchers.anyString(), Matchers.anyString())).thenReturn(queryMock);
	}

	@Test
	public void findByTenantIdElectionEventIdBallotId() throws ResourceNotFoundException {
		when(queryMock.getSingleResult()).thenReturn(new Ballot());

		String tenantId = "2";
		String ballotId = "2";
		String electionEventId = "2";
		assertNotNull(ballotRepository.findByTenantIdElectionEventIdBallotId(tenantId, electionEventId, ballotId));
	}

	@Test
	public void findByTenantIdElectionEventIdBallotIdNotFound() throws ResourceNotFoundException {
		when(queryMock.getSingleResult()).thenThrow(new NoResultException());

		expectedException.expect(ResourceNotFoundException.class);

		String tenantId = "2";
		String ballotId = "2";
		String electionEventId = "2";
		ballotRepository.findByTenantIdElectionEventIdBallotId(tenantId, electionEventId, ballotId);
	}
}
