【发布时间】:2016-05-21 17:39:34
【问题描述】:
我是 web 开发和 java 的新手。我已经使用 xml 开发了这个 rest-api,它运行良好(NetBeans)。但是,我需要对其进行单元测试。有人可以指导我吗?
提前致谢
@Path("/users")
public class users{
String host=HelperClass.host;
String uName=HelperClass.uName;
String pass=HelperClass.pass;
Connection con;
/**
* Gets all the users in the database with the password.
* @return
* @throws SQLException
*/
@GET
@Path("/getusers")
@Produces(MediaType.APPLICATION_XML)
public UserList getAllUsers() throws SQLException {
UserList users;
try
{
con=DriverManager.getConnection(host, uName, pass);
Statement stmt=con.createStatement();
String Sql="SELECT * FROM USERS";
ResultSet rs=stmt.executeQuery(Sql);
users=new UserList();
users.setUsers(new ArrayList<Users>());
while(rs.next())
{
Users newuser=new Users();
newuser.setUsername(rs.getString("username"));
newuser.setPassword(rs.getString("password"));
users.getUsers().add(newuser);
}
}
catch(Exception ex)
{
users=new UserList();
}
finally
{
con.close();
}
return users;
}
/**
* Gets the specific user in the database.
* @param userId
* @return
* @throws SQLException
*/
@GET
@Path("/getuser/{userId}")
@Produces(MediaType.APPLICATION_XML)
public Users getUser(@PathParam("userId") String userId) throws SQLException
{
Users user;
try
{
con=DriverManager.getConnection(host, uName, pass);
Statement stmt=con.createStatement();
String Sql="SELECT * FROM USERS where USERNAME='"+userId+"'";
ResultSet rs=stmt.executeQuery(Sql);
user=new Users();
while(rs.next())
{
user.setUsername(rs.getString("username"));
user.setPassword(rs.getString("password"));
}
}
catch(Exception ex)
{
user=new Users();
}
finally
{
con.close();
}
return user;
}
@POST
@Path("/setuser")
@Consumes({MediaType.APPLICATION_XML})
@Produces({MediaType.TEXT_PLAIN})
public String setUser(Users user) throws SQLException
{
try
{
con=DriverManager.getConnection(host, uName, pass);
Statement stmt=con.createStatement();
String Sql="INSERT INTO USERS VALUES('"+user.getUsername()+"','"+user.getPassword()+"')";
stmt.executeUpdate(Sql);
}
catch(Exception ex)
{
return "error";
}
finally
{
con.close();
}
return "done";
}
@DELETE
@Path("/deleteuser/{userId}")
@Produces({MediaType.TEXT_PLAIN})
public String deleteUser(@PathParam("userId") String userId) throws SQLException
{
try
{
con=DriverManager.getConnection(host, uName, pass);
Statement stmt=con.createStatement();
String Sql="Delete from replies where REPLY_ID='"+userId+"'";
stmt.executeUpdate(Sql);
Sql="Delete from comments where USER_ID='"+userId+"'";
stmt.executeUpdate(Sql);
Sql="Delete from USERINFO where USERINFO_ID='"+userId+"'";
stmt.executeUpdate(Sql);
Sql="Delete from USERS where USERNAME='"+userId+"'";
stmt.executeUpdate(Sql);
}
catch(Exception ex)
{
return "error";
}
finally
{
con.close();
}
return "done";
}
}
【问题讨论】:
标签: java xml rest unit-testing