Commit 63347867 authored by Administrator's avatar Administrator

Testing improvement

Several testing improvement have been done:
	- Cobertura plugin was replaced by JaCoCo plugin that supports Java 8
syntax.
	- Unit tests with a controller fixtured using EasyMock were added for
PeopleDAO and PeopleResource.
	- POM was reviewed, reordered and reformatted.
	- Test classes naming was reviewed and standarized.
	- Three test suites were added to group the unit, integration, and
acceptance tests.
	- Naming context management done in TestUtils was improved. 
parent a42e8ca4
...@@ -16,8 +16,12 @@ ...@@ -16,8 +16,12 @@
</licenses> </licenses>
<properties> <properties>
<!-- General -->
<maven.compiler.source>1.8</maven.compiler.source> <maven.compiler.source>1.8</maven.compiler.source>
<maven.compiler.target>1.8</maven.compiler.target> <maven.compiler.target>1.8</maven.compiler.target>
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
<!-- Dependencies -->
<jersey.version>2.15</jersey.version> <jersey.version>2.15</jersey.version>
<mysql.version>5.1.34</mysql.version> <mysql.version>5.1.34</mysql.version>
<commons.dbcp.version>1.4</commons.dbcp.version> <commons.dbcp.version>1.4</commons.dbcp.version>
...@@ -25,7 +29,13 @@ ...@@ -25,7 +29,13 @@
<junit.version>4.12</junit.version> <junit.version>4.12</junit.version>
<selenium.java.version>2.44.0</selenium.java.version> <selenium.java.version>2.44.0</selenium.java.version>
<spring.test.version>4.1.4.RELEASE</spring.test.version> <spring.test.version>4.1.4.RELEASE</spring.test.version>
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding> <easymock.version>3.3.1</easymock.version>
<!-- Plugins -->
<jacoco.version>0.7.2.201409121644</jacoco.version>
<surefire.version>2.18.1</surefire.version>
<maven.war.plugin.version>2.6</maven.war.plugin.version>
<tomcat.maven.plugin.version>2.2</tomcat.maven.plugin.version>
</properties> </properties>
<dependencies> <dependencies>
...@@ -89,20 +99,21 @@ ...@@ -89,20 +99,21 @@
<version>${spring.test.version}</version> <version>${spring.test.version}</version>
<scope>test</scope> <scope>test</scope>
</dependency> </dependency>
<dependency>
<groupId>org.easymock</groupId>
<artifactId>easymock</artifactId>
<version>${easymock.version}</version>
<scope>test</scope>
</dependency>
</dependencies> </dependencies>
<reporting> <reporting>
<plugins> <plugins>
<plugin>
<groupId>org.codehaus.mojo</groupId>
<artifactId>cobertura-maven-plugin</artifactId>
<version>2.6</version>
</plugin>
<plugin> <plugin>
<groupId>org.apache.maven.plugins</groupId> <groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-report-plugin</artifactId> <artifactId>maven-surefire-report-plugin</artifactId>
<version>2.18.1</version> <version>${surefire.version}</version>
<reportSets> <reportSets>
<reportSet> <reportSet>
<id>integration-tests</id> <id>integration-tests</id>
...@@ -122,34 +133,76 @@ ...@@ -122,34 +133,76 @@
<plugin> <plugin>
<artifactId>maven-war-plugin</artifactId> <artifactId>maven-war-plugin</artifactId>
<groupId>org.apache.maven.plugins</groupId> <groupId>org.apache.maven.plugins</groupId>
<version>2.6</version> <version>${maven.war.plugin.version}</version>
<configuration> <configuration>
<warName>DAAExample</warName> <warName>DAAExample</warName>
</configuration> </configuration>
</plugin> </plugin>
<plugin>
<groupId>org.jacoco</groupId>
<artifactId>jacoco-maven-plugin</artifactId>
<version>${jacoco.version}</version>
<executions>
<execution>
<id>default-prepare-agent</id>
<goals>
<goal>prepare-agent</goal>
</goals>
</execution>
<execution>
<id>default-prepare-agent-integration</id>
<goals>
<goal>prepare-agent-integration</goal>
</goals>
</execution>
<execution>
<id>coverage-report</id>
<phase>test</phase>
<goals>
<goal>report</goal>
</goals>
</execution>
<execution>
<id>coverage-report-integration</id>
<phase>integration-test</phase>
<goals>
<goal>report-integration</goal>
</goals>
</execution>
<execution>
<id>default-check</id>
<goals>
<goal>check</goal>
</goals>
</execution>
</executions>
</plugin>
<plugin> <plugin>
<groupId>org.apache.maven.plugins</groupId> <groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId> <artifactId>maven-surefire-plugin</artifactId>
<version>2.18.1</version> <version>${surefire.version}</version>
<configuration> <configuration>
<excludes> <includes>
<exclude>**/*WebTest*</exclude> <includes>**/UnitTestSuite.java</includes>
</excludes> </includes>
</configuration> </configuration>
</plugin> </plugin>
<plugin> <plugin>
<groupId>org.apache.maven.plugins</groupId> <groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-failsafe-plugin</artifactId> <artifactId>maven-failsafe-plugin</artifactId>
<version>2.18.1</version> <version>${surefire.version}</version>
<configuration> <configuration>
<includes> <includes>
<include>**/*WebTest*</include> <includes>**/IntegrationTestSuite.java</includes>
<includes>**/AcceptanceTestSuite.java</includes>
</includes> </includes>
</configuration> </configuration>
<executions> <executions>
<execution> <execution>
<id>default-integration-tests</id>
<goals> <goals>
<goal>integration-test</goal> <goal>integration-test</goal>
<goal>verify</goal> <goal>verify</goal>
...@@ -161,7 +214,7 @@ ...@@ -161,7 +214,7 @@
<plugin> <plugin>
<groupId>org.apache.maven.plugins</groupId> <groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-report-plugin</artifactId> <artifactId>maven-surefire-report-plugin</artifactId>
<version>2.18.1</version> <version>${surefire.version}</version>
<executions> <executions>
<execution> <execution>
...@@ -185,7 +238,7 @@ ...@@ -185,7 +238,7 @@
<plugin> <plugin>
<groupId>org.apache.tomcat.maven</groupId> <groupId>org.apache.tomcat.maven</groupId>
<artifactId>tomcat7-maven-plugin</artifactId> <artifactId>tomcat7-maven-plugin</artifactId>
<version>2.2</version> <version>${tomcat.maven.plugin.version}</version>
<configuration> <configuration>
<port>9080</port> <port>9080</port>
<path>/DAAExample</path> <path>/DAAExample</path>
...@@ -213,5 +266,38 @@ ...@@ -213,5 +266,38 @@
</executions> </executions>
</plugin> </plugin>
</plugins> </plugins>
<pluginManagement>
<plugins>
<!--This plugin's configuration is used to store Eclipse m2e settings only. It has no influence on the Maven build itself.-->
<plugin>
<groupId>org.eclipse.m2e</groupId>
<artifactId>lifecycle-mapping</artifactId>
<version>1.0.0</version>
<configuration>
<lifecycleMappingMetadata>
<pluginExecutions>
<pluginExecution>
<pluginExecutionFilter>
<groupId>org.jacoco</groupId>
<artifactId>
jacoco-maven-plugin
</artifactId>
<versionRange>
[0.7.2.201409121644,)
</versionRange>
<goals>
<goal>prepare-agent</goal>
</goals>
</pluginExecutionFilter>
<action>
<ignore></ignore>
</action>
</pluginExecution>
</pluginExecutions>
</lifecycleMappingMetadata>
</configuration>
</plugin>
</plugins>
</pluginManagement>
</build> </build>
</project> </project>
...@@ -15,7 +15,9 @@ import es.uvigo.esei.daa.rest.PeopleResource; ...@@ -15,7 +15,9 @@ import es.uvigo.esei.daa.rest.PeopleResource;
public class DAAExampleApplication extends Application { public class DAAExampleApplication extends Application {
@Override @Override
public Set<Class<?>> getClasses() { public Set<Class<?>> getClasses() {
return new HashSet<>(Arrays.asList(PeopleResource.class)); return new HashSet<>(Arrays.asList(
PeopleResource.class
));
} }
@Override @Override
......
...@@ -14,7 +14,7 @@ public abstract class DAO { ...@@ -14,7 +14,7 @@ public abstract class DAO {
private final static Logger LOG = Logger.getLogger("DAO"); private final static Logger LOG = Logger.getLogger("DAO");
private final static String JNDI_NAME = "java:/comp/env/jdbc/daaexample"; private final static String JNDI_NAME = "java:/comp/env/jdbc/daaexample";
private final DataSource dataSource; private DataSource dataSource;
public DAO() { public DAO() {
Context initContext; Context initContext;
......
...@@ -20,10 +20,10 @@ public class PeopleDAO extends DAO { ...@@ -20,10 +20,10 @@ public class PeopleDAO extends DAO {
try (final Connection conn = this.getConnection()) { try (final Connection conn = this.getConnection()) {
final String query = "SELECT * FROM people WHERE id=?"; final String query = "SELECT * FROM people WHERE id=?";
try (PreparedStatement statement = conn.prepareStatement(query)) { try (final PreparedStatement statement = conn.prepareStatement(query)) {
statement.setInt(1, id); statement.setInt(1, id);
try (ResultSet result = statement.executeQuery()) { try (final ResultSet result = statement.executeQuery()) {
if (result.next()) { if (result.next()) {
return new Person( return new Person(
result.getInt("id"), result.getInt("id"),
...@@ -43,8 +43,10 @@ public class PeopleDAO extends DAO { ...@@ -43,8 +43,10 @@ public class PeopleDAO extends DAO {
public List<Person> list() throws DAOException { public List<Person> list() throws DAOException {
try (final Connection conn = this.getConnection()) { try (final Connection conn = this.getConnection()) {
try (Statement statement = conn.createStatement()) { final String query = "SELECT * FROM people";
try (ResultSet result = statement.executeQuery("SELECT * FROM people")) {
try (final PreparedStatement statement = conn.prepareStatement(query)) {
try (final ResultSet result = statement.executeQuery()) {
final List<Person> people = new LinkedList<>(); final List<Person> people = new LinkedList<>();
while (result.next()) { while (result.next()) {
...@@ -69,7 +71,7 @@ public class PeopleDAO extends DAO { ...@@ -69,7 +71,7 @@ public class PeopleDAO extends DAO {
try (final Connection conn = this.getConnection()) { try (final Connection conn = this.getConnection()) {
final String query = "DELETE FROM people WHERE id=?"; final String query = "DELETE FROM people WHERE id=?";
try (PreparedStatement statement = conn.prepareStatement(query)) { try (final PreparedStatement statement = conn.prepareStatement(query)) {
statement.setInt(1, id); statement.setInt(1, id);
if (statement.executeUpdate() != 1) { if (statement.executeUpdate() != 1) {
...@@ -88,7 +90,7 @@ public class PeopleDAO extends DAO { ...@@ -88,7 +90,7 @@ public class PeopleDAO extends DAO {
throw new IllegalArgumentException("name and surname can't be null"); throw new IllegalArgumentException("name and surname can't be null");
} }
try (final Connection conn = this.getConnection()) { try (Connection conn = this.getConnection()) {
final String query = "UPDATE people SET name=?, surname=? WHERE id=?"; final String query = "UPDATE people SET name=?, surname=? WHERE id=?";
try (PreparedStatement statement = conn.prepareStatement(query)) { try (PreparedStatement statement = conn.prepareStatement(query)) {
...@@ -114,7 +116,7 @@ public class PeopleDAO extends DAO { ...@@ -114,7 +116,7 @@ public class PeopleDAO extends DAO {
throw new IllegalArgumentException("name and surname can't be null"); throw new IllegalArgumentException("name and surname can't be null");
} }
try (final Connection conn = this.getConnection()) { try (Connection conn = this.getConnection()) {
final String query = "INSERT INTO people VALUES(null, ?, ?)"; final String query = "INSERT INTO people VALUES(null, ?, ?)";
try (PreparedStatement statement = conn.prepareStatement(query, Statement.RETURN_GENERATED_KEYS)) { try (PreparedStatement statement = conn.prepareStatement(query, Statement.RETURN_GENERATED_KEYS)) {
......
...@@ -17,10 +17,10 @@ public class UsersDAO extends DAO { ...@@ -17,10 +17,10 @@ public class UsersDAO extends DAO {
try (final Connection conn = this.getConnection()) { try (final Connection conn = this.getConnection()) {
final String query = "SELECT password FROM users WHERE login=?"; final String query = "SELECT password FROM users WHERE login=?";
try (PreparedStatement statement = conn.prepareStatement(query)) { try (final PreparedStatement statement = conn.prepareStatement(query)) {
statement.setString(1, login); statement.setString(1, login);
try (ResultSet result = statement.executeQuery()) { try (final ResultSet result = statement.executeQuery()) {
if (result.next()) { if (result.next()) {
final String dbPassword = result.getString("password"); final String dbPassword = result.getString("password");
final String shaPassword = encodeSha256(password); final String shaPassword = encodeSha256(password);
...@@ -56,10 +56,10 @@ public class UsersDAO extends DAO { ...@@ -56,10 +56,10 @@ public class UsersDAO extends DAO {
try (final Connection conn = this.getConnection()) { try (final Connection conn = this.getConnection()) {
final String query = "SELECT password FROM users WHERE login=?"; final String query = "SELECT password FROM users WHERE login=?";
try (PreparedStatement statement = conn.prepareStatement(query)) { try (final PreparedStatement statement = conn.prepareStatement(query)) {
statement.setString(1, login); statement.setString(1, login);
try (ResultSet result = statement.executeQuery()) { try (final ResultSet result = statement.executeQuery()) {
if (result.next()) { if (result.next()) {
final String dbPassword = result.getString("password"); final String dbPassword = result.getString("password");
......
...@@ -37,4 +37,38 @@ public class Person { ...@@ -37,4 +37,38 @@ public class Person {
public void setSurname(String surname) { public void setSurname(String surname) {
this.surname = surname; this.surname = surname;
} }
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + id;
result = prime * result + ((name == null) ? 0 : name.hashCode());
result = prime * result + ((surname == null) ? 0 : surname.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
Person other = (Person) obj;
if (id != other.id)
return false;
if (name == null) {
if (other.name != null)
return false;
} else if (!name.equals(other.name))
return false;
if (surname == null) {
if (other.surname != null)
return false;
} else if (!surname.equals(other.surname))
return false;
return true;
}
} }
...@@ -25,13 +25,18 @@ public class PeopleResource { ...@@ -25,13 +25,18 @@ public class PeopleResource {
private final PeopleDAO dao; private final PeopleDAO dao;
public PeopleResource() { public PeopleResource() {
this.dao = new PeopleDAO(); this(new PeopleDAO());
}
// For testing purposes
PeopleResource(PeopleDAO dao) {
this.dao = dao;
} }
@GET @GET
public Response list() { public Response list() {
try { try {
return Response.ok(this.dao.list(), MediaType.APPLICATION_JSON).build(); return Response.ok(this.dao.list()).build();
} catch (DAOException e) { } catch (DAOException e) {
LOG.log(Level.SEVERE, "Error listing people", e); LOG.log(Level.SEVERE, "Error listing people", e);
return Response.serverError().entity(e.getMessage()).build(); return Response.serverError().entity(e.getMessage()).build();
...@@ -46,7 +51,7 @@ public class PeopleResource { ...@@ -46,7 +51,7 @@ public class PeopleResource {
try { try {
return Response.ok(this.dao.get(id), MediaType.APPLICATION_JSON).build(); return Response.ok(this.dao.get(id), MediaType.APPLICATION_JSON).build();
} catch (IllegalArgumentException iae) { } catch (IllegalArgumentException iae) {
iae.printStackTrace(); LOG.log(Level.FINE, "Invalid person id in get method", iae);
return Response.status(Response.Status.BAD_REQUEST) return Response.status(Response.Status.BAD_REQUEST)
.entity(iae.getMessage()).build(); .entity(iae.getMessage()).build();
} catch (DAOException e) { } catch (DAOException e) {
...@@ -65,7 +70,7 @@ public class PeopleResource { ...@@ -65,7 +70,7 @@ public class PeopleResource {
return Response.ok(id).build(); return Response.ok(id).build();
} catch (IllegalArgumentException iae) { } catch (IllegalArgumentException iae) {
iae.printStackTrace(); LOG.log(Level.FINE, "Invalid person id in delete method", iae);
return Response.status(Response.Status.BAD_REQUEST) return Response.status(Response.Status.BAD_REQUEST)
.entity(iae.getMessage()).build(); .entity(iae.getMessage()).build();
} catch (DAOException e) { } catch (DAOException e) {
...@@ -84,7 +89,7 @@ public class PeopleResource { ...@@ -84,7 +89,7 @@ public class PeopleResource {
try { try {
return Response.ok(this.dao.modify(id, name, surname)).build(); return Response.ok(this.dao.modify(id, name, surname)).build();
} catch (IllegalArgumentException iae) { } catch (IllegalArgumentException iae) {
iae.printStackTrace(); LOG.log(Level.FINE, "Invalid person id in modify method", iae);
return Response.status(Response.Status.BAD_REQUEST) return Response.status(Response.Status.BAD_REQUEST)
.entity(iae.getMessage()).build(); .entity(iae.getMessage()).build();
} catch (DAOException e) { } catch (DAOException e) {
...@@ -101,7 +106,7 @@ public class PeopleResource { ...@@ -101,7 +106,7 @@ public class PeopleResource {
try { try {
return Response.ok(this.dao.add(name, surname)).build(); return Response.ok(this.dao.add(name, surname)).build();
} catch (IllegalArgumentException iae) { } catch (IllegalArgumentException iae) {
iae.printStackTrace(); LOG.log(Level.FINE, "Invalid person id in add method", iae);
return Response.status(Response.Status.BAD_REQUEST) return Response.status(Response.Status.BAD_REQUEST)
.entity(iae.getMessage()).build(); .entity(iae.getMessage()).build();
} catch (DAOException e) { } catch (DAOException e) {
......
package es.uvigo.esei.daa;
import static org.easymock.EasyMock.anyString;
import static org.easymock.EasyMock.createMock;
import static org.easymock.EasyMock.createNiceMock;
import static org.easymock.EasyMock.expect;
import static org.easymock.EasyMock.replay;
import static org.easymock.EasyMock.reset;
import static org.easymock.EasyMock.verify;
import java.sql.Connection;
import java.sql.ResultSet;
import javax.sql.DataSource;
import org.junit.After;
import org.junit.Before;
import org.junit.BeforeClass;
import com.mysql.jdbc.PreparedStatement;
public abstract class DatabaseQueryUnitTest {
protected DataSource datasource;
protected Connection connection;
protected PreparedStatement statement;
protected ResultSet result;
protected boolean verify;
@BeforeClass
public static void setUpBeforeClass()
throws Exception {
TestUtils.clearTestDatabase();
TestUtils.clearContextBuilder();
}
@Before
public void setUp() throws Exception {
TestUtils.initTestDatabase();
datasource = createMock(DataSource.class);
connection = createMock(Connection.class);
statement = createNiceMock(PreparedStatement.class);
result = createMock(ResultSet.class);
expect(datasource.getConnection())
.andReturn(connection);
expect(connection.prepareStatement(anyString()))
.andReturn(statement);
expect(statement.executeQuery())
.andReturn(result)
.anyTimes(); // executeQuery is optional;
statement.close();
connection.close();
verify = true;
}
protected void resetAll() {
reset(result, statement, connection, datasource);
verify = false;
}
protected void replayAll()
throws Exception {
replay(result, statement, connection, datasource);
TestUtils.createFakeContext(datasource);
}
@After
public void tearDown() throws Exception {
TestUtils.clearTestDatabase();
TestUtils.clearContextBuilder();
try {
if (verify) {
verify(datasource, connection, statement, result);
verify = false;
}
} finally {
datasource = null;
connection = null;
statement = null;
result = null;
}
}
}
...@@ -15,15 +15,27 @@ import org.springframework.mock.jndi.SimpleNamingContextBuilder; ...@@ -15,15 +15,27 @@ import org.springframework.mock.jndi.SimpleNamingContextBuilder;
public final class TestUtils { public final class TestUtils {
private final static SimpleNamingContextBuilder CONTEXT_BUILDER
= new SimpleNamingContextBuilder();
private TestUtils() {} private TestUtils() {}
public static void createFakeContext() throws NamingException { public static void createFakeContext() throws NamingException {
final SimpleNamingContextBuilder builder = new SimpleNamingContextBuilder(); createFakeContext(createTestingDataSource());
builder.bind("java:/comp/env/jdbc/daaexample", createTestingDataSource()); }
builder.activate();
public static void createFakeContext(DataSource datasource)
throws IllegalStateException, NamingException {
CONTEXT_BUILDER.bind("java:/comp/env/jdbc/daaexample", datasource);
CONTEXT_BUILDER.activate();
} }
private static BasicDataSource createTestingDataSource() { public static void clearContextBuilder() {
CONTEXT_BUILDER.clear();
CONTEXT_BUILDER.deactivate();
}
public static BasicDataSource createTestingDataSource() {
final BasicDataSource ds = new BasicDataSource(); final BasicDataSource ds = new BasicDataSource();
ds.setDriverClassName("com.mysql.jdbc.Driver"); ds.setDriverClassName("com.mysql.jdbc.Driver");
ds.setUrl("jdbc:mysql://localhost:3306/daaexampletest?allowMultiQueries=true"); ds.setUrl("jdbc:mysql://localhost:3306/daaexampletest?allowMultiQueries=true");
...@@ -35,6 +47,10 @@ public final class TestUtils { ...@@ -35,6 +47,10 @@ public final class TestUtils {
return ds; return ds;
} }
public static BasicDataSource createEmptyDataSource() {
return new BasicDataSource();
}
public static void clearTestDatabase() throws SQLException { public static void clearTestDatabase() throws SQLException {
final String queries = new StringBuilder() final String queries = new StringBuilder()
.append("DELETE FROM `people`;") .append("DELETE FROM `people`;")
......
package es.uvigo.esei.daa.dao;
import static org.easymock.EasyMock.anyString;
import static org.easymock.EasyMock.eq;
import static org.easymock.EasyMock.expect;
import static org.easymock.EasyMock.reset;
import static org.junit.Assert.assertEquals;
import java.sql.SQLException;
import java.util.Arrays;
import java.util.List;
import org.junit.Test;
import es.uvigo.esei.daa.DatabaseQueryUnitTest;
import es.uvigo.esei.daa.entities.Person;
public class PeopleDAOUnitTest extends DatabaseQueryUnitTest {
@Test
public void testGet() throws Exception {
final Person person = new Person(1, "Pepe", "Pérez");
expect(result.next()).andReturn(true);
expect(result.getInt("id")).andReturn(person.getId());
expect(result.getString("name")).andReturn(person.getName());
expect(result.getString("surname")).andReturn(person.getSurname());
result.close();
replayAll();
final PeopleDAO peopleDAO = new PeopleDAO();
assertEquals("Unexpected person data",
person, peopleDAO.get(person.getId())
);
}
@Test(expected = IllegalArgumentException.class)
public void testGetMissing() throws Exception {
expect(result.next()).andReturn(false);
result.close();
replayAll();
final PeopleDAO peopleDAO = new PeopleDAO();
peopleDAO.get(2);
}
@Test(expected = DAOException.class)
public void testGetUnexpectedException() throws Exception {
expect(result.next()).andThrow(new SQLException());
result.close();
replayAll();
final PeopleDAO peopleDAO = new PeopleDAO();
peopleDAO.get(2);
}
@Test
public void testList() throws Exception {
final List<Person> people = Arrays.asList(
new Person(1, "Pepe", "Pérez"),
new Person(2, "Paco", "Martínez"),
new Person(3, "Martina", "Juárez")
);
for (Person person : people) {
expect(result.next()).andReturn(true);
expect(result.getInt("id")).andReturn(person.getId());
expect(result.getString("name")).andReturn(person.getName());
expect(result.getString("surname")).andReturn(person.getSurname());
}
expect(result.next()).andReturn(false);
result.close();
replayAll();
final PeopleDAO peopleDAO = new PeopleDAO();
assertEquals("Unexpected people data",
people, peopleDAO.list()
);
}
@Test(expected = DAOException.class)
public void testListUnexpectedException() throws Exception {
expect(result.next()).andThrow(new SQLException());
result.close();
replayAll();
final PeopleDAO peopleDAO = new PeopleDAO();
peopleDAO.list();
}
@Test
public void testAdd() throws Exception {
final Person person = new Person(1, "Pepe", "Pérez");
reset(connection);
expect(connection.prepareStatement(anyString(), eq(1)))
.andReturn(statement);
expect(statement.executeUpdate()).andReturn(1);
expect(statement.getGeneratedKeys()).andReturn(result);
expect(result.next()).andReturn(true);
expect(result.getInt(1)).andReturn(person.getId()); // Key retrieval
connection.close();
result.close();
replayAll();
final PeopleDAO peopleDAO = new PeopleDAO();
final Person newPerson = peopleDAO.add(person.getName(), person.getSurname());
assertEquals(person, newPerson);
}
@Test(expected = IllegalArgumentException.class)
public void testAddNullName() throws Exception {
replayAll();
final PeopleDAO peopleDAO = new PeopleDAO();
resetAll(); // No expectations
peopleDAO.add(null, "Pepe");
}
@Test(expected = IllegalArgumentException.class)
public void testAddNullSurname() throws Exception {
replayAll();
final PeopleDAO peopleDAO = new PeopleDAO();
resetAll(); // No expectations
peopleDAO.add("Pepe", null);
}
@Test(expected = DAOException.class)
public void testAddZeroUpdatedRows() throws Exception {
reset(connection);
expect(connection.prepareStatement(anyString(), eq(1)))
.andReturn(statement);
expect(statement.executeUpdate()).andReturn(0);
connection.close();
replayAll();
final PeopleDAO peopleDAO = new PeopleDAO();
peopleDAO.add("Paco", "Pérez");
}
@Test(expected = DAOException.class)
public void testAddNoGeneratedKey() throws Exception {
reset(connection);
expect(connection.prepareStatement(anyString(), eq(1)))
.andReturn(statement);
expect(statement.executeUpdate()).andReturn(1);
expect(statement.getGeneratedKeys()).andReturn(result);
expect(result.next()).andReturn(false);
result.close();
connection.close();
replayAll();
final PeopleDAO peopleDAO = new PeopleDAO();
peopleDAO.add("Paco", "Pérez");
}
@Test(expected = DAOException.class)
public void testAddUnexpectedException() throws Exception {
reset(connection);
expect(connection.prepareStatement(anyString(), eq(1)))
.andReturn(statement);
expect(statement.executeUpdate()).andThrow(new SQLException());
connection.close();
replayAll();
final PeopleDAO peopleDAO = new PeopleDAO();
peopleDAO.add("Paco", "Pérez");
}
@Test
public void testDelete() throws Exception {
expect(statement.executeUpdate()).andReturn(1);
replayAll();
final PeopleDAO peopleDAO = new PeopleDAO();
peopleDAO.delete(1);
}
@Test(expected = IllegalArgumentException.class)
public void testDeleteInvalidId() throws Exception {
expect(statement.executeUpdate()).andReturn(0);
replayAll();
final PeopleDAO peopleDAO = new PeopleDAO();
peopleDAO.delete(1);
}
@Test(expected = DAOException.class)
public void testDeleteUnexpectedException() throws Exception {
expect(statement.executeUpdate()).andThrow(new SQLException());
replayAll();
final PeopleDAO peopleDAO = new PeopleDAO();
peopleDAO.delete(1);
}
@Test
public void testModify() throws Exception {
final Person person = new Person(1, "Pepe", "Pérez");
expect(statement.executeUpdate()).andReturn(1);
replayAll();
final PeopleDAO peopleDAO = new PeopleDAO();
final Person newPerson = peopleDAO.modify(
person.getId(), person.getName(), person.getSurname()
);
assertEquals(person, newPerson);
}
@Test(expected = IllegalArgumentException.class)
public void testModifyNullName() throws Exception {
replayAll();
final PeopleDAO peopleDAO = new PeopleDAO();
resetAll(); // No expectations
peopleDAO.modify(1, null, "Pepe");
}
@Test(expected = IllegalArgumentException.class)
public void testModifyNullSurname() throws Exception {
replayAll();
final PeopleDAO peopleDAO = new PeopleDAO();
resetAll(); // No expectations
peopleDAO.modify(1, "Pepe", null);
}
@Test(expected = IllegalArgumentException.class)
public void testModifyZeroUpdatedRows() throws Exception {
expect(statement.executeUpdate()).andReturn(0);
replayAll();
final PeopleDAO peopleDAO = new PeopleDAO();
peopleDAO.modify(1, "Paco", "Pérez");
}
@Test(expected = DAOException.class)
public void testModifyUnexpectedException() throws Exception {
expect(statement.executeUpdate()).andThrow(new SQLException());
replayAll();
final PeopleDAO peopleDAO = new PeopleDAO();
peopleDAO.modify(1, "Paco", "Pérez");
}
}
...@@ -27,7 +27,7 @@ import com.fasterxml.jackson.jaxrs.json.JacksonJsonProvider; ...@@ -27,7 +27,7 @@ import com.fasterxml.jackson.jaxrs.json.JacksonJsonProvider;
import es.uvigo.esei.daa.TestUtils; import es.uvigo.esei.daa.TestUtils;
import es.uvigo.esei.daa.entities.Person; import es.uvigo.esei.daa.entities.Person;
public class PeopleTest extends JerseyTest { public class PeopleResourceTest extends JerseyTest {
@BeforeClass @BeforeClass
public static void setUpBeforeClass() throws Exception { public static void setUpBeforeClass() throws Exception {
TestUtils.createFakeContext(); TestUtils.createFakeContext();
......
package es.uvigo.esei.daa.rest;
import static org.easymock.EasyMock.anyInt;
import static org.easymock.EasyMock.anyString;
import static org.easymock.EasyMock.createMock;
import static org.easymock.EasyMock.expect;
import static org.easymock.EasyMock.expectLastCall;
import static org.easymock.EasyMock.replay;
import static org.easymock.EasyMock.verify;
import static org.junit.Assert.assertEquals;
import java.util.Arrays;
import java.util.List;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.Response.Status;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import es.uvigo.esei.daa.dao.DAOException;
import es.uvigo.esei.daa.dao.PeopleDAO;
import es.uvigo.esei.daa.entities.Person;
public class PeopleResourceUnitTest {
private PeopleDAO daoMock;
private PeopleResource resource;
@Before
public void setUp() throws Exception {
daoMock = createMock(PeopleDAO.class);
resource = new PeopleResource(daoMock);
}
@After
public void tearDown() throws Exception {
try {
verify(daoMock);
} finally {
daoMock = null;
resource = null;
}
}
@Test
public void testList() throws Exception {
final List<Person> people = Arrays.asList(
new Person(1, "Pepe", "Pérez"),
new Person(2, "Paco", "Martínez"),
new Person(3, "Martina", "Juárez")
);
expect(daoMock.list()).andReturn(people);
replay(daoMock);
final Response response = resource.list();
assertEquals(people, response.getEntity());
assertEquals(Status.OK, response.getStatusInfo());
}
@Test
public void testListDAOException() throws Exception {
expect(daoMock.list()).andThrow(new DAOException());
replay(daoMock);
final Response response = resource.list();
assertEquals(Status.INTERNAL_SERVER_ERROR, response.getStatusInfo());
}
@Test
public void testGet() throws Exception {
final Person person = new Person(1, "Pepe", "Pérez");
expect(daoMock.get(person.getId())).andReturn(person);
replay(daoMock);
final Response response = resource.get(person.getId());
assertEquals(person, response.getEntity());
assertEquals(Status.OK, response.getStatusInfo());
}
@Test
public void testGetDAOException() throws Exception {
expect(daoMock.get(anyInt())).andThrow(new DAOException());
replay(daoMock);
final Response response = resource.get(1);
assertEquals(Status.INTERNAL_SERVER_ERROR, response.getStatusInfo());
}
@Test
public void testGetIllegalArgumentException() throws Exception {
expect(daoMock.get(anyInt())).andThrow(new IllegalArgumentException());
replay(daoMock);
final Response response = resource.get(1);
assertEquals(Status.BAD_REQUEST, response.getStatusInfo());
}
@Test
public void testDelete() throws Exception {
daoMock.delete(anyInt());
replay(daoMock);
final Response response = resource.delete(1);
assertEquals(Status.OK, response.getStatusInfo());
}
@Test
public void testDeleteDAOException() throws Exception {
daoMock.delete(anyInt());
expectLastCall().andThrow(new DAOException());
replay(daoMock);
final Response response = resource.delete(1);
assertEquals(Status.INTERNAL_SERVER_ERROR, response.getStatusInfo());
}
@Test
public void testDeleteIllegalArgumentException() throws Exception {
daoMock.delete(anyInt());
expectLastCall().andThrow(new IllegalArgumentException());
replay(daoMock);
final Response response = resource.delete(1);
assertEquals(Status.BAD_REQUEST, response.getStatusInfo());
}
@Test
public void testModify() throws Exception {
final Person person = new Person(1, "Pepe", "Pérez");
expect(daoMock.modify(person.getId(), person.getName(), person.getSurname()))
.andReturn(person);
replay(daoMock);
final Response response = resource.modify(
person.getId(), person.getName(), person.getSurname());
assertEquals(person, response.getEntity());
assertEquals(Status.OK, response.getStatusInfo());
}
@Test
public void testModifyDAOException() throws Exception {
expect(daoMock.modify(anyInt(), anyString(), anyString()))
.andThrow(new DAOException());
replay(daoMock);
final Response response = resource.modify(1, "Paco", "Pérez");
assertEquals(Status.INTERNAL_SERVER_ERROR, response.getStatusInfo());
}
@Test
public void testModifyIllegalArgumentException() throws Exception {
expect(daoMock.modify(anyInt(), anyString(), anyString()))
.andThrow(new IllegalArgumentException());
replay(daoMock);
final Response response = resource.modify(1, "Paco", "Pérez");
assertEquals(Status.BAD_REQUEST, response.getStatusInfo());
}
@Test
public void testAdd() throws Exception {
final Person person = new Person(1, "Pepe", "Pérez");
expect(daoMock.add(person.getName(), person.getSurname()))
.andReturn(person);
replay(daoMock);
final Response response = resource.add(
person.getName(), person.getSurname());
assertEquals(person, response.getEntity());
assertEquals(Status.OK, response.getStatusInfo());
}
@Test
public void testAddDAOException() throws Exception {
expect(daoMock.add(anyString(), anyString()))
.andThrow(new DAOException());
replay(daoMock);
final Response response = resource.add("Paco", "Pérez");
assertEquals(Status.INTERNAL_SERVER_ERROR, response.getStatusInfo());
}
@Test
public void testAddIllegalArgumentException() throws Exception {
expect(daoMock.add(anyString(), anyString()))
.andThrow(new IllegalArgumentException());
replay(daoMock);
final Response response = resource.add("Paco", "Pérez");
assertEquals(Status.BAD_REQUEST, response.getStatusInfo());
}
}
package es.uvigo.esei.daa.suites;
import org.junit.runners.Suite.SuiteClasses;
import es.uvigo.esei.daa.web.PeopleWebTest;
@SuiteClasses({
PeopleWebTest.class
})
public class AcceptanceTestSuite {
}
package es.uvigo.esei.daa; package es.uvigo.esei.daa.suites;
import org.junit.runner.RunWith; import org.junit.runner.RunWith;
import org.junit.runners.Suite; import org.junit.runners.Suite;
import org.junit.runners.Suite.SuiteClasses; import org.junit.runners.Suite.SuiteClasses;
import es.uvigo.esei.daa.dao.PeopleDAOTest; import es.uvigo.esei.daa.dao.PeopleDAOTest;
import es.uvigo.esei.daa.rest.PeopleTest; import es.uvigo.esei.daa.rest.PeopleResourceTest;
import es.uvigo.esei.daa.web.PeopleWebTest; import es.uvigo.esei.daa.web.PeopleWebTest;
@SuiteClasses({ PeopleDAOTest.class, PeopleTest.class, PeopleWebTest.class }) @SuiteClasses({
PeopleDAOTest.class,
PeopleResourceTest.class,
PeopleWebTest.class
})
@RunWith(Suite.class) @RunWith(Suite.class)
public class PeopleTestSuite { public class IntegrationTestSuite {
} }
package es.uvigo.esei.daa.suites;
import org.junit.runner.RunWith;
import org.junit.runners.Suite;
import org.junit.runners.Suite.SuiteClasses;
import es.uvigo.esei.daa.dao.PeopleDAOUnitTest;
import es.uvigo.esei.daa.rest.PeopleResourceUnitTest;
@SuiteClasses({
PeopleDAOUnitTest.class,
PeopleResourceUnitTest.class
})
@RunWith(Suite.class)
public class UnitTestSuite {
}
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment