src_fm_fc_ms_ff
stringlengths 43
86.8k
| target
stringlengths 20
276k
|
---|---|
ScheduledCall implements Call<T> { @Override public boolean isExecuted() { return delegate.isExecuted(); } ScheduledCall(Call<T> delegate, Executor callbackExecutor); @Override T execute(); @Override void enqueue(final Callback<T> callback); @Override boolean isExecuted(); @Override void cancel(); @Override boolean isCanceled(); @SuppressWarnings("CloneDoesntCallSuperClone") // Performing deep clone. @Override ScheduledCall<T> clone(); }
|
@SuppressWarnings("ConstantConditions") @Test public void isExecuted_ReturnsDelegateState() throws Exception { boolean expectedValue = true; when(wrappedCall.isExecuted()).thenReturn(expectedValue); boolean actualValue = testCall.isExecuted(); verify(wrappedCall).isExecuted(); assertEquals(actualValue, expectedValue); }
|
ScheduledCall implements Call<T> { @Override public boolean isCanceled() { return delegate.isCanceled(); } ScheduledCall(Call<T> delegate, Executor callbackExecutor); @Override T execute(); @Override void enqueue(final Callback<T> callback); @Override boolean isExecuted(); @Override void cancel(); @Override boolean isCanceled(); @SuppressWarnings("CloneDoesntCallSuperClone") // Performing deep clone. @Override ScheduledCall<T> clone(); }
|
@SuppressWarnings("ConstantConditions") @Test public void isCancelled_ReturnsDelegateState() throws Exception { boolean expectedValue = true; when(wrappedCall.isCanceled()).thenReturn(expectedValue); boolean actualValue = testCall.isCanceled(); verify(wrappedCall).isCanceled(); assertEquals(actualValue, expectedValue); }
|
ScheduledCall implements Call<T> { @Override public void enqueue(final Callback<T> callback) { if (callback == null) { throw new IllegalArgumentException("Callback argument cannot be null."); } delegate.enqueue(new Callback<T>() { @Override public void onResponse(Call<T> call, final T response) { callbackExecutor.execute(new Runnable() { @Override public void run() { callback.onResponse(ScheduledCall.this, response); } }); } @Override public void onFailure(Call<T> call, final Throwable t) { callbackExecutor.execute(new Runnable() { @Override public void run() { callback.onFailure(ScheduledCall.this, t); } }); } }); } ScheduledCall(Call<T> delegate, Executor callbackExecutor); @Override T execute(); @Override void enqueue(final Callback<T> callback); @Override boolean isExecuted(); @Override void cancel(); @Override boolean isCanceled(); @SuppressWarnings("CloneDoesntCallSuperClone") // Performing deep clone. @Override ScheduledCall<T> clone(); }
|
@Test public void enqueue_Throws_WithNullArgument() throws Exception { expectedException.expect(IllegalArgumentException.class); testCall.enqueue(null); }
@Test public void enqueue_CallsDelegateMethodWithNonNullArgument() throws Exception { testCall.enqueue(testCallback); verify(wrappedCall).enqueue(callbackArgumentCaptor.capture()); Callback passedCallback = callbackArgumentCaptor.getValue(); assertNotNull(passedCallback); }
|
ScheduledCall implements Call<T> { @SuppressWarnings("CloneDoesntCallSuperClone") @Override public ScheduledCall<T> clone() { return new ScheduledCall<>(delegate.clone(), callbackExecutor); } ScheduledCall(Call<T> delegate, Executor callbackExecutor); @Override T execute(); @Override void enqueue(final Callback<T> callback); @Override boolean isExecuted(); @Override void cancel(); @Override boolean isCanceled(); @SuppressWarnings("CloneDoesntCallSuperClone") // Performing deep clone. @Override ScheduledCall<T> clone(); }
|
@Test public void clone_ReturnsNewObject() throws Exception { Call<Object> clonedObject = testCall.clone(); assertNotNull(clonedObject); assertNotEquals(testCall, clonedObject); }
|
OkHttpCall implements Call<T> { @Override public void cancel() { rawCall.cancel(); } OkHttpCall(okhttp3.Call rawCall, ResponseAdapter<T> adapter); @Override T execute(); @Override void enqueue(final Callback<T> callback); @Override boolean isExecuted(); @Override void cancel(); @Override boolean isCanceled(); @SuppressWarnings("CloneDoesntCallSuperClone") @Override OkHttpCall<T> clone(); }
|
@Test public void cancel_CallsDelegateMethod() throws Exception { testCall.cancel(); verify(mockOkHttpCall).cancel(); }
|
OkHttpCall implements Call<T> { @Override public boolean isExecuted() { return rawCall.isExecuted(); } OkHttpCall(okhttp3.Call rawCall, ResponseAdapter<T> adapter); @Override T execute(); @Override void enqueue(final Callback<T> callback); @Override boolean isExecuted(); @Override void cancel(); @Override boolean isCanceled(); @SuppressWarnings("CloneDoesntCallSuperClone") @Override OkHttpCall<T> clone(); }
|
@SuppressWarnings("ConstantConditions") @Test public void isExecuted_ReturnsDelegateState() throws Exception { boolean expectedValue = true; when(mockOkHttpCall.isExecuted()).thenReturn(expectedValue); boolean actualValue = testCall.isExecuted(); verify(mockOkHttpCall).isExecuted(); assertEquals(actualValue, expectedValue); }
|
OkHttpCall implements Call<T> { @Override public boolean isCanceled() { return rawCall.isCanceled(); } OkHttpCall(okhttp3.Call rawCall, ResponseAdapter<T> adapter); @Override T execute(); @Override void enqueue(final Callback<T> callback); @Override boolean isExecuted(); @Override void cancel(); @Override boolean isCanceled(); @SuppressWarnings("CloneDoesntCallSuperClone") @Override OkHttpCall<T> clone(); }
|
@SuppressWarnings("ConstantConditions") @Test public void isCancelled_ReturnsDelegateState() throws Exception { boolean expectedValue = true; when(mockOkHttpCall.isCanceled()).thenReturn(expectedValue); boolean actualValue = testCall.isCanceled(); verify(mockOkHttpCall).isCanceled(); assertEquals(actualValue, expectedValue); }
|
OkHttpCall implements Call<T> { @Override public void enqueue(final Callback<T> callback) { if (callback == null) { throw new IllegalArgumentException("Callback argument cannot be null."); } rawCall.enqueue(new okhttp3.Callback() { @Override public void onFailure(okhttp3.Call call, IOException e) { callback.onFailure(OkHttpCall.this, e); } @Override public void onResponse(okhttp3.Call call, Response response) throws IOException { try { callback.onResponse(OkHttpCall.this, adapt(response)); } catch (ApiError | IOException e) { closeQuietly(response); callback.onFailure(OkHttpCall.this, e); } } }); } OkHttpCall(okhttp3.Call rawCall, ResponseAdapter<T> adapter); @Override T execute(); @Override void enqueue(final Callback<T> callback); @Override boolean isExecuted(); @Override void cancel(); @Override boolean isCanceled(); @SuppressWarnings("CloneDoesntCallSuperClone") @Override OkHttpCall<T> clone(); }
|
@Test public void enqueue_Throws_WithNullArgument() throws Exception { expectedException.expect(IllegalArgumentException.class); testCall.enqueue(null); }
@Test public void enqueue_CallsDelegateMethodWithNonNullArgument() throws Exception { testCall.enqueue(testCallback); verify(mockOkHttpCall).enqueue(callbackArgumentCaptor.capture()); okhttp3.Callback passedCallback = callbackArgumentCaptor.getValue(); assertNotNull(passedCallback); }
@Test public void enqueue_CallsFailureMethod_OnDelegateFailureCalled() throws Exception { testCall.enqueue(testCallback); verify(mockOkHttpCall).enqueue(callbackArgumentCaptor.capture()); okhttp3.Callback passedCallback = callbackArgumentCaptor.getValue(); assertNotNull(passedCallback); IOException error = new IOException("something wrong"); passedCallback.onFailure(mockOkHttpCall, error); verify(testCallback).onFailure(eq(testCall), eq(error)); }
|
OkHttpCall implements Call<T> { @SuppressWarnings("CloneDoesntCallSuperClone") @Override public OkHttpCall<T> clone() { return new OkHttpCall<>(rawCall.clone(), responseAdapter); } OkHttpCall(okhttp3.Call rawCall, ResponseAdapter<T> adapter); @Override T execute(); @Override void enqueue(final Callback<T> callback); @Override boolean isExecuted(); @Override void cancel(); @Override boolean isCanceled(); @SuppressWarnings("CloneDoesntCallSuperClone") @Override OkHttpCall<T> clone(); }
|
@Test public void clone_ReturnsNewObject() throws Exception { Call<Object> clonedObject = testCall.clone(); assertNotNull(clonedObject); assertNotEquals(testCall, clonedObject); }
|
UserService { public void register(User user) throws UserExistException{ User u = this.getUserByUserName(user.getUserName()); if(u != null){ throw new UserExistException("用户名已经存在"); }else{ user.setCredit(100); user.setUserType(1); userDao.save(user); } } @Autowired void setUserDao(UserDao userDao); @Autowired void setLoginLogDao(LoginLogDao loginLogDao); void register(User user); void update(User user); User getUserByUserName(String userName); User getUserById(int userId); void lockUser(String userName); void unlockUser(String userName); List<User> queryUserByUserName(String userName); List<User> getAllUsers(); void loginSuccess(User user); }
|
@Test public void register() throws UserExistException{ User user = new User(); user.setUserName("tom"); user.setPassword("1234"); doAnswer(new Answer<User>() { public User answer(InvocationOnMock invocation) { Object[] args = invocation.getArguments(); User user = (User) args[0]; if (user != null) { user.setUserId(1); } return user; } }).when(userDao).save(user); userService.register(user); assertEquals(user.getUserId(), 1); verify(userDao, times(1)).save(user); }
|
ForumService { public void addBoardManager(int boardId,String userName){ User user = userDao.getUserByUserName(userName); if(user == null){ throw new RuntimeException("用户名为"+userName+"的用户不存在。"); }else{ Board board = boardDao.get(boardId); user.getManBoards().add(board); userDao.update(user); } } @Autowired void setTopicDao(TopicDao topicDao); @Autowired void setUserDao(UserDao userDao); @Autowired void setBoardDao(BoardDao boardDao); @Autowired void setPostDao(PostDao postDao); void addTopic(Topic topic); void removeTopic(int topicId); void addPost(Post post); void removePost(int postId); void addBoard(Board board); void removeBoard(int boardId); void makeDigestTopic(int topicId); List<Board> getAllBoards(); Page getPagedTopics(int boardId,int pageNo,int pageSize); Page getPagedPosts(int topicId,int pageNo,int pageSize); Page queryTopicByTitle(String title,int pageNo,int pageSize); Board getBoardById(int boardId); Topic getTopicByTopicId(int topicId); Post getPostByPostId(int postId); void addBoardManager(int boardId,String userName); void updateTopic(Topic topic); void updatePost(Post post); }
|
@Test @DataSet("XiaoChun.DataSet.xls") public void addBoardManager(){ forumService.addBoardManager(1,"tom"); User userDb = userService.getUserByUserName("tom"); assertEquals(userDb.getManBoards().size(), greaterThan(0)); }
|
ForumDao { public void addForums(final List<Forum> forums) { final String sql = "INSERT INTO t_forum(forum_name,forum_desc) VALUES(?,?)"; jdbcTemplate.batchUpdate(sql, new BatchPreparedStatementSetter() { public int getBatchSize() { return forums.size(); } public void setValues(PreparedStatement ps, int index) throws SQLException { Forum forum = forums.get(index); ps.setString(1, forum.getForumName()); ps.setString(2, forum.getForumDesc()); } }); } @Autowired void setJdbcTemplate(JdbcTemplate jdbcTemplate); @Autowired void setNamedParameterJdbcTemplate(NamedParameterJdbcTemplate namedParameterJdbcTemplate); void initDb(); void addForum(final Forum forum); void addForumByNamedParams(final Forum forum); void addForums(final List<Forum> forums); Forum getForum(final int forumId); List<Forum> getForums(final int fromId, final int toId); }
|
@Test public void testAddForums() throws Throwable { List<Forum> forums = new ArrayList<Forum>(); for(int i =0 ;i< 100000 ;i++){ Forum f1 = new Forum(); f1.setForumName("爱美妈妈"); f1.setForumDesc("减肥、塑身、化妆品"); forums.add(f1); } forumDao.addForums(forums); }
|
ForumDao { public void addForum(final Forum forum) { final String sql = "INSERT INTO t_forum(forum_name,forum_desc) VALUES(?,?)"; Object[] params = new Object[] { forum.getForumName(), forum.getForumDesc() }; KeyHolder keyHolder = new GeneratedKeyHolder(); jdbcTemplate.update(new PreparedStatementCreator() { public PreparedStatement createPreparedStatement(Connection conn) throws SQLException { PreparedStatement ps = conn.prepareStatement(sql, Statement.RETURN_GENERATED_KEYS); ps.setString(1, forum.getForumName()); ps.setString(2, forum.getForumDesc()); return ps; } }, keyHolder); forum.setForumId(keyHolder.getKey().intValue()); } @Autowired void setJdbcTemplate(JdbcTemplate jdbcTemplate); @Autowired void setNamedParameterJdbcTemplate(NamedParameterJdbcTemplate namedParameterJdbcTemplate); void initDb(); void addForum(final Forum forum); void addForumByNamedParams(final Forum forum); void addForums(final List<Forum> forums); Forum getForum(final int forumId); List<Forum> getForums(final int fromId, final int toId); }
|
@Test public void testAddForum() { Forum forum = new Forum(); forum.setForumName("1二手市场"); forum.setForumDesc("1二手货物的交流论坛。"); forumDao.addForum(forum); System.out.println(forum.getForumId()); }
|
ForumDao { public void addForumByNamedParams(final Forum forum) { final String sql = "INSERT INTO t_forum(forum_name, forum_desc) VALUES(:forumName,:forumDesc)"; SqlParameterSource sps = new BeanPropertySqlParameterSource(forum); namedParameterJdbcTemplate.update(sql, sps); } @Autowired void setJdbcTemplate(JdbcTemplate jdbcTemplate); @Autowired void setNamedParameterJdbcTemplate(NamedParameterJdbcTemplate namedParameterJdbcTemplate); void initDb(); void addForum(final Forum forum); void addForumByNamedParams(final Forum forum); void addForums(final List<Forum> forums); Forum getForum(final int forumId); List<Forum> getForums(final int fromId, final int toId); }
|
@Test public void testAddForumByNamedParams() { Forum forum = new Forum(); forum.setForumName("2二手市场"); forum.setForumDesc("2二手货物的交流论坛。"); forumDao.addForumByNamedParams(forum); }
|
ForumOODao { public Forum getForum(int forumId){ return forumQuery.findObject(forumId); } @Autowired void setDataSource(DataSource dataSource); @PostConstruct void init(); Forum getForum(int forumId); void addForum(Forum forum); int getTopicNum(int userId); int getForumNum(); }
|
@Test public void testGetForum(){ jdbcTemplate.execute(" insert into t_forum(forum_name,forum_desc) "+ " values('test','test')"); int forumId = jdbcTemplate.queryForObject("select max(forum_id) from t_forum",Integer.class); Forum forum = forumDao.getForum(forumId); System.out.println(forum.getForumName()); }
|
ForumOODao { public void addForum(Forum forum){ forumInsert.insert(forum); } @Autowired void setDataSource(DataSource dataSource); @PostConstruct void init(); Forum getForum(int forumId); void addForum(Forum forum); int getTopicNum(int userId); int getForumNum(); }
|
@Test public void testAddForum(){ Forum forum = new Forum(); forum.setForumName("test2"); forum.setForumDesc("desc 2"); forumDao.addForum(forum); }
|
ForumOODao { public int getTopicNum(int userId){ return getTopicNum.getTopicNum(userId); } @Autowired void setDataSource(DataSource dataSource); @PostConstruct void init(); Forum getForum(int forumId); void addForum(Forum forum); int getTopicNum(int userId); int getForumNum(); }
|
@Test public void testGetTopicNum(){ int topicNum = forumDao.getTopicNum(1); System.out.println("topicNum:"+topicNum); }
|
PostDao { public void addPost(final Post post){ String sql = " INSERT INTO t_post(post_id,user_id,post_text,post_attach)" + " VALUES(?,?,?,?)"; jdbcTemplate.execute(sql,new AbstractLobCreatingPreparedStatementCallback(this.lobHandler) { protected void setValues(PreparedStatement ps,LobCreator lobCreator) throws SQLException { ps.setInt(1, incre.nextIntValue()); ps.setInt(2, post.getUserId()); lobCreator.setClobAsString(ps, 3, post.getPostText()); lobCreator.setBlobAsBytes(ps, 4, post.getPostAttach()); } }); } @Autowired void setJdbcTemplate(JdbcTemplate jdbcTemplate); @Autowired void setLobHandler(LobHandler lobHandler); @Autowired void setIncre(DataFieldMaxValueIncrementer incre); void addPost(final Post post); void getNativeConn(); List<Post> getAttachs(final int userId); void getAttach(final int postId, final OutputStream os); }
|
@Test public void testAddPost() throws Throwable{ Post post = new Post(); post.setUserId(2); ClassPathResource res = new ClassPathResource("temp.jpg"); byte[] mockImg = FileCopyUtils.copyToByteArray(res.getFile()); post.setPostAttach(mockImg); post.setPostText("测试帖子的内容"); postDao.addPost(post); }
|
PostDao { public void getAttach(final int postId, final OutputStream os) { String sql = "SELECT post_attach FROM t_post WHERE post_id=? "; jdbcTemplate.query(sql, new Object[] {postId}, new AbstractLobStreamingResultSetExtractor() { protected void handleNoRowFound() throws LobRetrievalFailureException { System.out.println("Not Found result!"); } public void streamData(ResultSet rs) throws SQLException,IOException { InputStream is = lobHandler.getBlobAsBinaryStream(rs, 1); if (is != null) { FileCopyUtils.copy(is, os); } } } ); } @Autowired void setJdbcTemplate(JdbcTemplate jdbcTemplate); @Autowired void setLobHandler(LobHandler lobHandler); @Autowired void setIncre(DataFieldMaxValueIncrementer incre); void addPost(final Post post); void getNativeConn(); List<Post> getAttachs(final int userId); void getAttach(final int postId, final OutputStream os); }
|
@Test public void testgetAttach() throws Throwable{ FileOutputStream fos = new FileOutputStream("d:/temp.jpg"); postDao.getAttach(1,fos); }
|
UserService { public User getUserByUserName(String userName){ return userDao.getUserByUserName(userName); } @Autowired void setUserDao(UserDao userDao); @Autowired void setLoginLogDao(LoginLogDao loginLogDao); void register(User user); void update(User user); User getUserByUserName(String userName); User getUserById(int userId); void lockUser(String userName); void unlockUser(String userName); List<User> queryUserByUserName(String userName); List<User> getAllUsers(); void loginSuccess(User user); }
|
@Test public void getUserByUserName() { User user = new User(); user.setUserName("tom"); user.setPassword("1234"); user.setCredit(100); doReturn(user).when(userDao).getUserByUserName("tom"); User u = userService.getUserByUserName("tom"); assertNotNull(u); assertEquals(u.getUserName(), user.getUserName()); verify(userDao, times(1)).getUserByUserName("tom"); }
|
PostDao { public List<Post> getAttachs(final int userId) { String sql = " SELECT post_id,post_attach FROM t_post where user_id =? and post_attach is not null "; return jdbcTemplate.query(sql, new Object[] { userId }, new RowMapper<Post>() { public Post mapRow(ResultSet rs, int rowNum) throws SQLException { int postId = rs.getInt(1); byte[] attach = lobHandler.getBlobAsBytes(rs, 2); Post post = new Post(); post.setPostId(postId); post.setPostAttach(attach); return post; } }); } @Autowired void setJdbcTemplate(JdbcTemplate jdbcTemplate); @Autowired void setLobHandler(LobHandler lobHandler); @Autowired void setIncre(DataFieldMaxValueIncrementer incre); void addPost(final Post post); void getNativeConn(); List<Post> getAttachs(final int userId); void getAttach(final int postId, final OutputStream os); }
|
@Test public void testgetAttachs() throws Throwable{ Post post = new Post(); post.setUserId(2); ClassPathResource res = new ClassPathResource("temp.jpg"); byte[] mockImg = FileCopyUtils.copyToByteArray(res.getFile()); post.setPostAttach(mockImg); post.setPostText("测试帖子的内容"); postDao.addPost(post); List<Post> list = postDao.getAttachs(3); for (Post tempPost:list) { System.out.println(tempPost.getPostId()+";"+post.getPostAttach().length); } }
|
TopicDao { public double getReplyRate(int userId) { String sql = "SELECT topic_replies,topic_views FROM t_topic WHERE user_id=?"; double rate = jdbcTemplate.queryForObject(sql, new Object[] { userId }, new RowMapper<Double>() { public Double mapRow(ResultSet rs, int index) throws SQLException { int replies = rs.getInt("topic_replies"); int views = rs.getInt("topic_views"); if (views > 0) return new Double((double) replies / views); else return new Double(0.0); } }); return rate; } @Autowired void setJdbcTemplate(JdbcTemplate jdbcTemplate); double getReplyRate(int userId); int getUserTopicNum(final int userId); int getUserTopicNum2(int userId); SqlRowSet getTopicRowSet(int userId); }
|
@Test public void testGetReplyRate() { double rate = topicDao.getReplyRate(2); System.out.println("rate is:" + rate); }
|
TopicDao { public int getUserTopicNum(final int userId) { String sql = "{call P_GET_TOPIC_NUM(?,?)}"; CallableStatementCreatorFactory fac = new CallableStatementCreatorFactory(sql); fac.addParameter(new SqlParameter("userId",Types.INTEGER)); fac.addParameter(new SqlOutParameter("topicNum",Types.INTEGER)); Map<String,Integer> paramsMap = new HashMap<String,Integer>(); paramsMap.put("userId",userId); CallableStatementCreator csc = fac.newCallableStatementCreator (paramsMap); Integer num = jdbcTemplate.execute(csc,new CallableStatementCallback<Integer>(){ public Integer doInCallableStatement(CallableStatement cs) throws SQLException, DataAccessException { cs.execute(); return cs.getInt(2); } }); return num; } @Autowired void setJdbcTemplate(JdbcTemplate jdbcTemplate); double getReplyRate(int userId); int getUserTopicNum(final int userId); int getUserTopicNum2(int userId); SqlRowSet getTopicRowSet(int userId); }
|
@Test public void testGetUserTopicNum() throws Throwable { int num = topicDao.getUserTopicNum(1); System.out.println("num is:" + num); }
|
TopicDao { public SqlRowSet getTopicRowSet(int userId) { String sql = "SELECT topic_id,topic_title FROM t_topic WHERE user_id=?"; return jdbcTemplate.queryForRowSet(sql,userId); } @Autowired void setJdbcTemplate(JdbcTemplate jdbcTemplate); double getReplyRate(int userId); int getUserTopicNum(final int userId); int getUserTopicNum2(int userId); SqlRowSet getTopicRowSet(int userId); }
|
@Test public void testGetTopicRowSet() { SqlRowSet srs = topicDao.getTopicRowSet(1); while (srs.next()) { System.out.println(srs.getString("topic_id")); } }
|
LoginController { @RequestMapping(value = "/loginCheck.html") public ModelAndView loginCheck(HttpServletRequest request){ User user = new User(); user.setUserName(request.getParameter("userName")); user.setPassword(request.getParameter("password")); boolean isValidUser = userService.hasMatchUser(user.getUserName(), user.getPassword()); if (!isValidUser) { return new ModelAndView("login", "error", "用户名或密码错误。"); } else { user = userService.findUserByUserName(user .getUserName()); user.setLastIp(request.getLocalAddr()); user.setLastVisit(new Date()); userService.loginSuccess(user); request.getSession().setAttribute("user", user); return new ModelAndView("main"); } } @RequestMapping(value = "/index.html") String loginPage(); @RequestMapping(value = "/loginCheck.html") ModelAndView loginCheck(HttpServletRequest request); @Autowired void setUserService(UserService userService); }
|
@Test public void loginCheckByMock() throws Exception { request.setRequestURI("/loginCheck.html"); request.addParameter("userName", "tom"); request.addParameter("password", "123456"); ModelAndView mav = controller.loginCheck(request); User user = (User) request.getSession().getAttribute("user"); assertNotNull(mav); assertEquals(mav.getViewName(), "main"); assertNotNull(user); assertThat(user.getUserName(), equalTo("tom")); assertThat(user.getCredit(), greaterThan(5)); }
|
MailSender implements ApplicationContextAware { public void sendMail(String to){ System.out.println("MailSender:模拟发送邮件..."); MailSendEvent mse = new MailSendEvent(this.ctx,to); ctx.publishEvent(mse); } void setApplicationContext(ApplicationContext ctx); void sendMail(String to); }
|
@Test public void testMailSender() { MailSender mailSender = (MailSender)ctx.getBean("mailSender"); mailSender.sendMail("[email protected]"); }
|
UserService { public boolean hasMatchUser(String userName, String password) { int matchCount =userDao.getMatchCount(userName, password); return matchCount > 0; } boolean hasMatchUser(String userName, String password); User findUserByUserName(String userName); @Transactional void loginSuccess(User user); @Autowired void setUserDao(UserDao userDao); @Autowired void setLoginLogDao(LoginLogDao loginLogDao); }
|
@Test public void testHasMatchUser() { boolean b1 = userService.hasMatchUser("admin", "123456"); boolean b2 = userService.hasMatchUser("admin", "1111"); assertTrue(b1); assertTrue(!b2); }
|
UserService { public User findUserByUserName(String userName) { return userDao.findUserByUserName(userName); } boolean hasMatchUser(String userName, String password); User findUserByUserName(String userName); @Transactional void loginSuccess(User user); @Autowired void setUserDao(UserDao userDao); @Autowired void setLoginLogDao(LoginLogDao loginLogDao); }
|
@Test public void testFindUserByUserName()throws Exception{ for(int i =0; i< 100;i++) { User user = userService.findUserByUserName("admin"); assertEquals(user.getUserName(), "admin"); } }
|
CastorSample { public static void objectToXml() { try { User user = getUser(); FileWriter writer = new FileWriter("out/CastorSampe.xml"); Mapping mapping = new Mapping(); String mappingFile = ResourceUtils.getResourceFullPath( CastorSample.class, "mapping.xml"); mapping.loadMapping(mappingFile); Marshaller marshaller = new Marshaller(writer); marshaller.setMapping(mapping); marshaller.setEncoding("GBK"); marshaller.marshal(user); } catch (Exception e) { e.printStackTrace(System.err); } } static User getUser(); static void objectToXml(); static User xmlToObject(); static void main(String[] args); }
|
@Test public void objectToXml()throws Exception { CastorSample.objectToXml(); FileReader reader = new FileReader("out/CastorSampe.xml"); BufferedReader br = new BufferedReader(reader); StringBuffer sb = new StringBuffer(""); String s; while ((s = br.readLine()) != null) { sb.append(s); } reader.close(); br.close(); assertXpathExists(" assertXpathExists(" assertXpathExists(" assertXpathExists(" }
|
CastorSample { public static User xmlToObject() { try { FileReader reader = new FileReader("out/CastorSampe.xml"); Mapping mapping = new Mapping(); String mappingFile = ResourceUtils.getResourceFullPath( CastorSample.class, "mapping.xml"); mapping.loadMapping(mappingFile); Unmarshaller unmar = new Unmarshaller(mapping); User u = (User) unmar.unmarshal(reader); System.out.println("用户名: " + u.getUserName()); for (LoginLog log : u.getLogs()) { System.out.println("访问IP: " + log.getIp()); System.out.println("访问时间: " + log.getLoginDate()); } return u; } catch (Exception e) { System.err.println(e.getMessage()); e.printStackTrace(System.err); } return null; } static User getUser(); static void objectToXml(); static User xmlToObject(); static void main(String[] args); }
|
@Test public void xmlToObject() { CastorSample.objectToXml(); User u = CastorSample.xmlToObject(); assertNotNull(u); assertEquals("castor", u.getUserName()); for (LoginLog log : u.getLogs()) { assertNotNull(log); assertNotNull(log.getIp()); assertNotNull(log.getLoginDate()); } }
|
UserService { public void lockUser(String userName){ User user = userDao.getUserByUserName(userName); user.setLocked(User.USER_LOCK); userDao.update(user); } @Autowired void setUserDao(UserDao userDao); @Autowired void setLoginLogDao(LoginLogDao loginLogDao); void register(User user); void update(User user); User getUserByUserName(String userName); User getUserById(int userId); void lockUser(String userName); void unlockUser(String userName); List<User> queryUserByUserName(String userName); List<User> getAllUsers(); void loginSuccess(User user); }
|
@Test public void lockUser() { User user = new User(); user.setUserName("tom"); user.setPassword("1234"); doReturn(user).when(userDao).getUserByUserName("tom"); doNothing().when(userDao).update(user); userService.lockUser("tom"); User u = userService.getUserByUserName("tom"); assertEquals(User.USER_LOCK, u.getLocked()); }
|
JibxSample { public static void objectToXml() { try { User user = getUser(); IBindingFactory bfact = BindingDirectory.getFactory(User.class); IMarshallingContext ctx = bfact.createMarshallingContext(); FileOutputStream outputStream = new FileOutputStream("out/JibxSample.xml"); ctx.marshalDocument(user, "UTF-8", null, outputStream); } catch (Exception ex) { ex.printStackTrace(); } } static User getUser(); static void objectToXml(); static User xmlToObject(); static void main(String[] args); }
|
@Test public void objectToXml()throws Exception { JibxSample.objectToXml(); }
|
JibxSample { public static User xmlToObject(){ try { IBindingFactory bfact = BindingDirectory.getFactory(User.class); IUnmarshallingContext uctx = bfact.createUnmarshallingContext(); File dataFile = new File("JibxSample.xml"); InputStream in = new FileInputStream(dataFile); User user = (User) uctx.unmarshalDocument(in, null); System.out.println("userName:" + user.getUserName()); for (LoginLog log : user.getLogs()) { if (log != null) { System.out.println("访问IP: " + log.getIp()); System.out.println("访问时间: " + log.getLoginDate()); } } return user; }catch (Exception e){ return null; } } static User getUser(); static void objectToXml(); static User xmlToObject(); static void main(String[] args); }
|
@Test public void xmlToObject() throws Exception { JibxSample.xmlToObject(); User u = JibxSample.xmlToObject(); }
|
XStreamSample { public static void objectToXml() throws Exception { User user = getUser(); FileOutputStream outputStream = new FileOutputStream("out/XStreamSample.xml"); xstream.toXML(user, outputStream); } static User getUser(); static void objectToXml(); static User xmlToObject(); static void main(String[] args); }
|
@Test public void objectToXml()throws Exception { XStreamSample.objectToXml(); FileReader reader = new FileReader("out/XStreamSample.xml"); BufferedReader br = new BufferedReader(reader); StringBuffer sb = new StringBuffer(""); String s; while ((s = br.readLine()) != null) { sb.append(s); } System.out.println(sb.toString()); reader.close(); br.close(); assertXpathExists(" assertXpathExists(" assertXpathExists(" assertXpathExists(" }
|
XStreamSample { public static User xmlToObject() throws Exception { FileInputStream fis = new FileInputStream("out/XStreamSample.xml"); User u = (User) xstream.fromXML(fis); for (LoginLog log : u.getLogs()) { if (log != null) { System.out.println("访问IP: " + log.getIp()); System.out.println("访问时间: " + log.getLoginDate()); } } return u; } static User getUser(); static void objectToXml(); static User xmlToObject(); static void main(String[] args); }
|
@Test public void xmlToObject()throws Exception { XStreamSample.objectToXml(); User u = XStreamSample.xmlToObject(); assertNotNull(u); assertEquals("xstream", u.getUserName()); for (LoginLog log : u.getLogs()) { assertNotNull(log); assertNotNull(log.getIp()); assertNotNull(log.getLoginDate()); } }
|
JaxbSample { public static void objectToXml() throws Exception { User user = getUser(); JAXBContext context = JAXBContext.newInstance(User.class); Marshaller m = context.createMarshaller(); m.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true); FileWriter writer = new FileWriter("out/JaxbSample.xml"); m.marshal(user, writer); } static User getUser(); static void objectToXml(); static User xmlToObject(); static void main(String args[]); }
|
@Test public void objectToXml()throws Exception { JaxbSample.objectToXml(); }
|
JaxbSample { public static User xmlToObject() throws Exception { JAXBContext context = JAXBContext.newInstance(User.class); FileReader reader = new FileReader("out/JaxbSample.xml"); Unmarshaller um = context.createUnmarshaller(); User u = (User) um.unmarshal(reader); for (LoginLog log : u.getLogs().getLoginLog()) { if (log != null) { System.out.println("访问IP: " + log.getIp()); System.out.println("访问时间: " + log.getLoginDate().getTime()); } } return u; } static User getUser(); static void objectToXml(); static User xmlToObject(); static void main(String args[]); }
|
@Test public void xmlToObject()throws Exception { JaxbSample.objectToXml(); User u = JaxbSample.xmlToObject(); assertNotNull(u); assertEquals("jaxb", u.getUserName()); for (LoginLog log : u.getLogs().getLoginLog()) { assertNotNull(log); assertNotNull(log.getIp()); assertNotNull(log.getLoginDate()); } }
|
UserController { @RequestMapping(value = "/handle41") public String handle41(@RequestBody String body) { System.out.println(body); return "success"; } @Autowired void setUserService(UserService userService); @RequestMapping(method = RequestMethod.POST) ModelAndView createUser(User user); @RequestMapping(value = "/register", method = RequestMethod.GET, params = "!myParam") String register(@ModelAttribute("user") User user); @RequestMapping(value = "/delete", method = RequestMethod.POST, params = "userId") String test1(@RequestParam("userId") String userId); @RequestMapping(value = "/show", headers = "content-type=text/*") String test2(@RequestParam("userId") String userId); @RequestMapping(value = "/handle1") String handle1(@RequestParam("userName") String userName,
@RequestParam("password") String password,
@RequestParam("realName") String realName); @RequestMapping(value = "/handle2") ModelAndView handle2(@CookieValue("JSESSIONID") String sessionId,
@RequestHeader("Accept-Language") String accpetLanguage); @RequestMapping(value = "/handle3") String handle3(User user); @RequestMapping(value = "/handle4") String handle4(HttpServletRequest request); @RequestMapping(value = "/handle11") String handle11(
@RequestParam(value = "userName", required = false) String userName,
@RequestParam("age") int age); @RequestMapping(value = "/handle12") String handle12(
@CookieValue(value = "sessionId", required = false) String sessionId,
@RequestParam("age") int age); @RequestMapping(value = "/handle13") String handle13(@RequestHeader("Accept-Encoding") String encoding,
@RequestHeader("Keep-Alive") long keepAlive); @RequestMapping(value = "/handle14") String handle14(User user); @RequestMapping(value = "/handle21") void handle21(HttpServletRequest request,
HttpServletResponse response); @RequestMapping(value = "/handle22") ModelAndView handle22(HttpServletRequest request); @RequestMapping(value = "/handle23") String handle23(HttpSession session); @RequestMapping(value = "/success") String success(); @RequestMapping(value = "/fail") String fail(); @RequestMapping(value = "/handle24") String handle24(HttpServletRequest request,
@RequestParam("userName") String userName); @RequestMapping(value = "/handle25") String handle25(WebRequest request); @RequestMapping(value = "/handle31") void handle31(OutputStream os); @RequestMapping(value = "/handle41") String handle41(@RequestBody String body); @ResponseBody @RequestMapping(value = "/handle42/{imageId}") byte[] handle42(@PathVariable("imageId") String imageId); @RequestMapping(value = "/handle43") String handle43(HttpEntity<String> requestEntity); @RequestMapping(value = "/handle44/{imageId}") ResponseEntity<byte[]> handle44(
@PathVariable("imageId") String imageId); @RequestMapping(value = "/handle51") ResponseEntity<User> handle51(HttpEntity<User> requestEntity); @RequestMapping(value = "/handle61") String handle61(@ModelAttribute("user") User user); @RequestMapping(value = "/handle62") String handle62(@ModelAttribute("user") User user); @RequestMapping(value = "/handle63") String handle63(ModelMap modelMap); @ModelAttribute("user") User getUser(); @ModelAttribute("user1") User getUser1(); @ModelAttribute("user2") User getUser2(); @ModelAttribute("dept") Dept getDept(); @RequestMapping(value = "/handle71") String handle71(@ModelAttribute("user") User user); @RequestMapping(value = "/handle72") String handle72(ModelMap modelMap, SessionStatus sessionStatus); @RequestMapping(value = "/handle81") String handle81(@RequestParam("user") User user, ModelMap modelMap); @RequestMapping(value = "/register2") String register2(User user); @RequestMapping(value = "/handle82") String handle82(User user); @RequestMapping(value = "/register3") String register3(); @RequestMapping(value = "/register4") String register4(); @RequestMapping(value = "/handle91") String handle91(@Valid @ModelAttribute("user") User user,
BindingResult bindingResult, ModelMap mm); @RequestMapping(value = "/handle92") String handle92(@ModelAttribute("user") User user,
BindingResult bindingResult); @RequestMapping(value = "/welcome") String handle100(); @RequestMapping(value = "/showUserList") String showUserList(ModelMap mm); @RequestMapping(value = "/showUserListByFtl") String showUserListInFtl(ModelMap mm); @RequestMapping(value = "/showUserListByXls") String showUserListInExcel(ModelMap mm); @RequestMapping(value = "/showUserListByPdf") String showUserListInPdf(ModelMap mm); @RequestMapping(value = "/showUserListByXml") String showUserListInXml(ModelMap mm); @RequestMapping(value = "/showUserListByJson") String showUserListInJson(ModelMap mm); @RequestMapping(value = "/showUserListByJson1") String showUserListInJson1(ModelMap mm); @RequestMapping(value = "/showUserListByI18n") String showUserListInI18n(ModelMap mm); @RequestMapping(value = "/showUserListMix") String showUserListMix(ModelMap mm); @RequestMapping(value = "/uploadPage") String updatePage(); @RequestMapping(value = "/upload") String updateThumb(@RequestParam("name") String name,
@RequestParam("file") MultipartFile file); @RequestMapping(value = "/throwException") String throwException(); @ExceptionHandler(RuntimeException.class) String handleException(RuntimeException re, HttpServletRequest request); @RequestMapping(value = "/notFound") String notFound(); @ResponseStatus(HttpStatus.NOT_FOUND) String notFound(HttpServletRequest request); @InitBinder void initBinder(WebDataBinder binder); }
|
@Test public void testhandle41() { RestTemplate restTemplate = new RestTemplate(); MultiValueMap<String, String> form = new LinkedMultiValueMap<String, String>(); form.add("userName", "tom"); form.add("password", "123456"); form.add("age", "45"); restTemplate.postForLocation( "http: }
|
UserController { @ResponseBody @RequestMapping(value = "/handle42/{imageId}") public byte[] handle42(@PathVariable("imageId") String imageId) throws IOException { System.out.println("load image of " + imageId); Resource res = new ClassPathResource("/image.jpg"); byte[] fileData = FileCopyUtils.copyToByteArray(res.getInputStream()); return fileData; } @Autowired void setUserService(UserService userService); @RequestMapping(method = RequestMethod.POST) ModelAndView createUser(User user); @RequestMapping(value = "/register", method = RequestMethod.GET, params = "!myParam") String register(@ModelAttribute("user") User user); @RequestMapping(value = "/delete", method = RequestMethod.POST, params = "userId") String test1(@RequestParam("userId") String userId); @RequestMapping(value = "/show", headers = "content-type=text/*") String test2(@RequestParam("userId") String userId); @RequestMapping(value = "/handle1") String handle1(@RequestParam("userName") String userName,
@RequestParam("password") String password,
@RequestParam("realName") String realName); @RequestMapping(value = "/handle2") ModelAndView handle2(@CookieValue("JSESSIONID") String sessionId,
@RequestHeader("Accept-Language") String accpetLanguage); @RequestMapping(value = "/handle3") String handle3(User user); @RequestMapping(value = "/handle4") String handle4(HttpServletRequest request); @RequestMapping(value = "/handle11") String handle11(
@RequestParam(value = "userName", required = false) String userName,
@RequestParam("age") int age); @RequestMapping(value = "/handle12") String handle12(
@CookieValue(value = "sessionId", required = false) String sessionId,
@RequestParam("age") int age); @RequestMapping(value = "/handle13") String handle13(@RequestHeader("Accept-Encoding") String encoding,
@RequestHeader("Keep-Alive") long keepAlive); @RequestMapping(value = "/handle14") String handle14(User user); @RequestMapping(value = "/handle21") void handle21(HttpServletRequest request,
HttpServletResponse response); @RequestMapping(value = "/handle22") ModelAndView handle22(HttpServletRequest request); @RequestMapping(value = "/handle23") String handle23(HttpSession session); @RequestMapping(value = "/success") String success(); @RequestMapping(value = "/fail") String fail(); @RequestMapping(value = "/handle24") String handle24(HttpServletRequest request,
@RequestParam("userName") String userName); @RequestMapping(value = "/handle25") String handle25(WebRequest request); @RequestMapping(value = "/handle31") void handle31(OutputStream os); @RequestMapping(value = "/handle41") String handle41(@RequestBody String body); @ResponseBody @RequestMapping(value = "/handle42/{imageId}") byte[] handle42(@PathVariable("imageId") String imageId); @RequestMapping(value = "/handle43") String handle43(HttpEntity<String> requestEntity); @RequestMapping(value = "/handle44/{imageId}") ResponseEntity<byte[]> handle44(
@PathVariable("imageId") String imageId); @RequestMapping(value = "/handle51") ResponseEntity<User> handle51(HttpEntity<User> requestEntity); @RequestMapping(value = "/handle61") String handle61(@ModelAttribute("user") User user); @RequestMapping(value = "/handle62") String handle62(@ModelAttribute("user") User user); @RequestMapping(value = "/handle63") String handle63(ModelMap modelMap); @ModelAttribute("user") User getUser(); @ModelAttribute("user1") User getUser1(); @ModelAttribute("user2") User getUser2(); @ModelAttribute("dept") Dept getDept(); @RequestMapping(value = "/handle71") String handle71(@ModelAttribute("user") User user); @RequestMapping(value = "/handle72") String handle72(ModelMap modelMap, SessionStatus sessionStatus); @RequestMapping(value = "/handle81") String handle81(@RequestParam("user") User user, ModelMap modelMap); @RequestMapping(value = "/register2") String register2(User user); @RequestMapping(value = "/handle82") String handle82(User user); @RequestMapping(value = "/register3") String register3(); @RequestMapping(value = "/register4") String register4(); @RequestMapping(value = "/handle91") String handle91(@Valid @ModelAttribute("user") User user,
BindingResult bindingResult, ModelMap mm); @RequestMapping(value = "/handle92") String handle92(@ModelAttribute("user") User user,
BindingResult bindingResult); @RequestMapping(value = "/welcome") String handle100(); @RequestMapping(value = "/showUserList") String showUserList(ModelMap mm); @RequestMapping(value = "/showUserListByFtl") String showUserListInFtl(ModelMap mm); @RequestMapping(value = "/showUserListByXls") String showUserListInExcel(ModelMap mm); @RequestMapping(value = "/showUserListByPdf") String showUserListInPdf(ModelMap mm); @RequestMapping(value = "/showUserListByXml") String showUserListInXml(ModelMap mm); @RequestMapping(value = "/showUserListByJson") String showUserListInJson(ModelMap mm); @RequestMapping(value = "/showUserListByJson1") String showUserListInJson1(ModelMap mm); @RequestMapping(value = "/showUserListByI18n") String showUserListInI18n(ModelMap mm); @RequestMapping(value = "/showUserListMix") String showUserListMix(ModelMap mm); @RequestMapping(value = "/uploadPage") String updatePage(); @RequestMapping(value = "/upload") String updateThumb(@RequestParam("name") String name,
@RequestParam("file") MultipartFile file); @RequestMapping(value = "/throwException") String throwException(); @ExceptionHandler(RuntimeException.class) String handleException(RuntimeException re, HttpServletRequest request); @RequestMapping(value = "/notFound") String notFound(); @ResponseStatus(HttpStatus.NOT_FOUND) String notFound(HttpServletRequest request); @InitBinder void initBinder(WebDataBinder binder); }
|
@Test public void testhandle42() throws IOException { RestTemplate restTemplate = new RestTemplate(); byte[] response = restTemplate.postForObject( "http: Resource outFile = new FileSystemResource("d:/image_copy.jpg"); FileCopyUtils.copy(response, outFile.getFile()); }
|
UserController { @RequestMapping(value = "/handle43") public String handle43(HttpEntity<String> requestEntity) { long contentLen = requestEntity.getHeaders().getContentLength(); System.out.println("user:" + requestEntity.getBody()); return "success"; } @Autowired void setUserService(UserService userService); @RequestMapping(method = RequestMethod.POST) ModelAndView createUser(User user); @RequestMapping(value = "/register", method = RequestMethod.GET, params = "!myParam") String register(@ModelAttribute("user") User user); @RequestMapping(value = "/delete", method = RequestMethod.POST, params = "userId") String test1(@RequestParam("userId") String userId); @RequestMapping(value = "/show", headers = "content-type=text/*") String test2(@RequestParam("userId") String userId); @RequestMapping(value = "/handle1") String handle1(@RequestParam("userName") String userName,
@RequestParam("password") String password,
@RequestParam("realName") String realName); @RequestMapping(value = "/handle2") ModelAndView handle2(@CookieValue("JSESSIONID") String sessionId,
@RequestHeader("Accept-Language") String accpetLanguage); @RequestMapping(value = "/handle3") String handle3(User user); @RequestMapping(value = "/handle4") String handle4(HttpServletRequest request); @RequestMapping(value = "/handle11") String handle11(
@RequestParam(value = "userName", required = false) String userName,
@RequestParam("age") int age); @RequestMapping(value = "/handle12") String handle12(
@CookieValue(value = "sessionId", required = false) String sessionId,
@RequestParam("age") int age); @RequestMapping(value = "/handle13") String handle13(@RequestHeader("Accept-Encoding") String encoding,
@RequestHeader("Keep-Alive") long keepAlive); @RequestMapping(value = "/handle14") String handle14(User user); @RequestMapping(value = "/handle21") void handle21(HttpServletRequest request,
HttpServletResponse response); @RequestMapping(value = "/handle22") ModelAndView handle22(HttpServletRequest request); @RequestMapping(value = "/handle23") String handle23(HttpSession session); @RequestMapping(value = "/success") String success(); @RequestMapping(value = "/fail") String fail(); @RequestMapping(value = "/handle24") String handle24(HttpServletRequest request,
@RequestParam("userName") String userName); @RequestMapping(value = "/handle25") String handle25(WebRequest request); @RequestMapping(value = "/handle31") void handle31(OutputStream os); @RequestMapping(value = "/handle41") String handle41(@RequestBody String body); @ResponseBody @RequestMapping(value = "/handle42/{imageId}") byte[] handle42(@PathVariable("imageId") String imageId); @RequestMapping(value = "/handle43") String handle43(HttpEntity<String> requestEntity); @RequestMapping(value = "/handle44/{imageId}") ResponseEntity<byte[]> handle44(
@PathVariable("imageId") String imageId); @RequestMapping(value = "/handle51") ResponseEntity<User> handle51(HttpEntity<User> requestEntity); @RequestMapping(value = "/handle61") String handle61(@ModelAttribute("user") User user); @RequestMapping(value = "/handle62") String handle62(@ModelAttribute("user") User user); @RequestMapping(value = "/handle63") String handle63(ModelMap modelMap); @ModelAttribute("user") User getUser(); @ModelAttribute("user1") User getUser1(); @ModelAttribute("user2") User getUser2(); @ModelAttribute("dept") Dept getDept(); @RequestMapping(value = "/handle71") String handle71(@ModelAttribute("user") User user); @RequestMapping(value = "/handle72") String handle72(ModelMap modelMap, SessionStatus sessionStatus); @RequestMapping(value = "/handle81") String handle81(@RequestParam("user") User user, ModelMap modelMap); @RequestMapping(value = "/register2") String register2(User user); @RequestMapping(value = "/handle82") String handle82(User user); @RequestMapping(value = "/register3") String register3(); @RequestMapping(value = "/register4") String register4(); @RequestMapping(value = "/handle91") String handle91(@Valid @ModelAttribute("user") User user,
BindingResult bindingResult, ModelMap mm); @RequestMapping(value = "/handle92") String handle92(@ModelAttribute("user") User user,
BindingResult bindingResult); @RequestMapping(value = "/welcome") String handle100(); @RequestMapping(value = "/showUserList") String showUserList(ModelMap mm); @RequestMapping(value = "/showUserListByFtl") String showUserListInFtl(ModelMap mm); @RequestMapping(value = "/showUserListByXls") String showUserListInExcel(ModelMap mm); @RequestMapping(value = "/showUserListByPdf") String showUserListInPdf(ModelMap mm); @RequestMapping(value = "/showUserListByXml") String showUserListInXml(ModelMap mm); @RequestMapping(value = "/showUserListByJson") String showUserListInJson(ModelMap mm); @RequestMapping(value = "/showUserListByJson1") String showUserListInJson1(ModelMap mm); @RequestMapping(value = "/showUserListByI18n") String showUserListInI18n(ModelMap mm); @RequestMapping(value = "/showUserListMix") String showUserListMix(ModelMap mm); @RequestMapping(value = "/uploadPage") String updatePage(); @RequestMapping(value = "/upload") String updateThumb(@RequestParam("name") String name,
@RequestParam("file") MultipartFile file); @RequestMapping(value = "/throwException") String throwException(); @ExceptionHandler(RuntimeException.class) String handleException(RuntimeException re, HttpServletRequest request); @RequestMapping(value = "/notFound") String notFound(); @ResponseStatus(HttpStatus.NOT_FOUND) String notFound(HttpServletRequest request); @InitBinder void initBinder(WebDataBinder binder); }
|
@Test public void testhandle43() { RestTemplate restTemplate = new RestTemplate(); MultiValueMap<String, String> form = new LinkedMultiValueMap<String, String>(); form.add("userName", "tom"); form.add("password", "123456"); form.add("age", "45"); restTemplate.postForLocation( "http: }
|
UserController { @RequestMapping(value = "/handle44/{imageId}") public ResponseEntity<byte[]> handle44( @PathVariable("imageId") String imageId) throws Throwable { Resource res = new ClassPathResource("/image.jpg"); byte[] fileData = FileCopyUtils.copyToByteArray(res.getInputStream()); ResponseEntity<byte[]> responseEntity = new ResponseEntity<byte[]>( fileData, HttpStatus.OK); return responseEntity; } @Autowired void setUserService(UserService userService); @RequestMapping(method = RequestMethod.POST) ModelAndView createUser(User user); @RequestMapping(value = "/register", method = RequestMethod.GET, params = "!myParam") String register(@ModelAttribute("user") User user); @RequestMapping(value = "/delete", method = RequestMethod.POST, params = "userId") String test1(@RequestParam("userId") String userId); @RequestMapping(value = "/show", headers = "content-type=text/*") String test2(@RequestParam("userId") String userId); @RequestMapping(value = "/handle1") String handle1(@RequestParam("userName") String userName,
@RequestParam("password") String password,
@RequestParam("realName") String realName); @RequestMapping(value = "/handle2") ModelAndView handle2(@CookieValue("JSESSIONID") String sessionId,
@RequestHeader("Accept-Language") String accpetLanguage); @RequestMapping(value = "/handle3") String handle3(User user); @RequestMapping(value = "/handle4") String handle4(HttpServletRequest request); @RequestMapping(value = "/handle11") String handle11(
@RequestParam(value = "userName", required = false) String userName,
@RequestParam("age") int age); @RequestMapping(value = "/handle12") String handle12(
@CookieValue(value = "sessionId", required = false) String sessionId,
@RequestParam("age") int age); @RequestMapping(value = "/handle13") String handle13(@RequestHeader("Accept-Encoding") String encoding,
@RequestHeader("Keep-Alive") long keepAlive); @RequestMapping(value = "/handle14") String handle14(User user); @RequestMapping(value = "/handle21") void handle21(HttpServletRequest request,
HttpServletResponse response); @RequestMapping(value = "/handle22") ModelAndView handle22(HttpServletRequest request); @RequestMapping(value = "/handle23") String handle23(HttpSession session); @RequestMapping(value = "/success") String success(); @RequestMapping(value = "/fail") String fail(); @RequestMapping(value = "/handle24") String handle24(HttpServletRequest request,
@RequestParam("userName") String userName); @RequestMapping(value = "/handle25") String handle25(WebRequest request); @RequestMapping(value = "/handle31") void handle31(OutputStream os); @RequestMapping(value = "/handle41") String handle41(@RequestBody String body); @ResponseBody @RequestMapping(value = "/handle42/{imageId}") byte[] handle42(@PathVariable("imageId") String imageId); @RequestMapping(value = "/handle43") String handle43(HttpEntity<String> requestEntity); @RequestMapping(value = "/handle44/{imageId}") ResponseEntity<byte[]> handle44(
@PathVariable("imageId") String imageId); @RequestMapping(value = "/handle51") ResponseEntity<User> handle51(HttpEntity<User> requestEntity); @RequestMapping(value = "/handle61") String handle61(@ModelAttribute("user") User user); @RequestMapping(value = "/handle62") String handle62(@ModelAttribute("user") User user); @RequestMapping(value = "/handle63") String handle63(ModelMap modelMap); @ModelAttribute("user") User getUser(); @ModelAttribute("user1") User getUser1(); @ModelAttribute("user2") User getUser2(); @ModelAttribute("dept") Dept getDept(); @RequestMapping(value = "/handle71") String handle71(@ModelAttribute("user") User user); @RequestMapping(value = "/handle72") String handle72(ModelMap modelMap, SessionStatus sessionStatus); @RequestMapping(value = "/handle81") String handle81(@RequestParam("user") User user, ModelMap modelMap); @RequestMapping(value = "/register2") String register2(User user); @RequestMapping(value = "/handle82") String handle82(User user); @RequestMapping(value = "/register3") String register3(); @RequestMapping(value = "/register4") String register4(); @RequestMapping(value = "/handle91") String handle91(@Valid @ModelAttribute("user") User user,
BindingResult bindingResult, ModelMap mm); @RequestMapping(value = "/handle92") String handle92(@ModelAttribute("user") User user,
BindingResult bindingResult); @RequestMapping(value = "/welcome") String handle100(); @RequestMapping(value = "/showUserList") String showUserList(ModelMap mm); @RequestMapping(value = "/showUserListByFtl") String showUserListInFtl(ModelMap mm); @RequestMapping(value = "/showUserListByXls") String showUserListInExcel(ModelMap mm); @RequestMapping(value = "/showUserListByPdf") String showUserListInPdf(ModelMap mm); @RequestMapping(value = "/showUserListByXml") String showUserListInXml(ModelMap mm); @RequestMapping(value = "/showUserListByJson") String showUserListInJson(ModelMap mm); @RequestMapping(value = "/showUserListByJson1") String showUserListInJson1(ModelMap mm); @RequestMapping(value = "/showUserListByI18n") String showUserListInI18n(ModelMap mm); @RequestMapping(value = "/showUserListMix") String showUserListMix(ModelMap mm); @RequestMapping(value = "/uploadPage") String updatePage(); @RequestMapping(value = "/upload") String updateThumb(@RequestParam("name") String name,
@RequestParam("file") MultipartFile file); @RequestMapping(value = "/throwException") String throwException(); @ExceptionHandler(RuntimeException.class) String handleException(RuntimeException re, HttpServletRequest request); @RequestMapping(value = "/notFound") String notFound(); @ResponseStatus(HttpStatus.NOT_FOUND) String notFound(HttpServletRequest request); @InitBinder void initBinder(WebDataBinder binder); }
|
@Test public void testhandle44() throws IOException { RestTemplate restTemplate = new RestTemplate(); byte[] response = restTemplate.postForObject( "http: Resource outFile = new FileSystemResource("d:/image_copy.jpg"); FileCopyUtils.copy(response, outFile.getFile()); }
|
UserService { public void unlockUser(String userName){ User user = userDao.getUserByUserName(userName); user.setLocked(User.USER_UNLOCK); userDao.update(user); } @Autowired void setUserDao(UserDao userDao); @Autowired void setLoginLogDao(LoginLogDao loginLogDao); void register(User user); void update(User user); User getUserByUserName(String userName); User getUserById(int userId); void lockUser(String userName); void unlockUser(String userName); List<User> queryUserByUserName(String userName); List<User> getAllUsers(); void loginSuccess(User user); }
|
@Test public void unlockUser() { User user = new User(); user.setUserName("tom"); user.setPassword("1234"); user.setLocked(User.USER_LOCK); doReturn(user).when(userDao).getUserByUserName("tom"); doNothing().when(userDao).update(user); userService.unlockUser("tom"); User u = userService.getUserByUserName("tom"); assertEquals(User.USER_UNLOCK, u.getLocked()); }
|
UserController { @RequestMapping(value = "/handle61") public String handle61(@ModelAttribute("user") User user) { user.setUserId("1000"); return "/user/createSuccess"; } @Autowired void setUserService(UserService userService); @RequestMapping(method = RequestMethod.POST) ModelAndView createUser(User user); @RequestMapping(value = "/register", method = RequestMethod.GET, params = "!myParam") String register(@ModelAttribute("user") User user); @RequestMapping(value = "/delete", method = RequestMethod.POST, params = "userId") String test1(@RequestParam("userId") String userId); @RequestMapping(value = "/show", headers = "content-type=text/*") String test2(@RequestParam("userId") String userId); @RequestMapping(value = "/handle1") String handle1(@RequestParam("userName") String userName,
@RequestParam("password") String password,
@RequestParam("realName") String realName); @RequestMapping(value = "/handle2") ModelAndView handle2(@CookieValue("JSESSIONID") String sessionId,
@RequestHeader("Accept-Language") String accpetLanguage); @RequestMapping(value = "/handle3") String handle3(User user); @RequestMapping(value = "/handle4") String handle4(HttpServletRequest request); @RequestMapping(value = "/handle11") String handle11(
@RequestParam(value = "userName", required = false) String userName,
@RequestParam("age") int age); @RequestMapping(value = "/handle12") String handle12(
@CookieValue(value = "sessionId", required = false) String sessionId,
@RequestParam("age") int age); @RequestMapping(value = "/handle13") String handle13(@RequestHeader("Accept-Encoding") String encoding,
@RequestHeader("Keep-Alive") long keepAlive); @RequestMapping(value = "/handle14") String handle14(User user); @RequestMapping(value = "/handle21") void handle21(HttpServletRequest request,
HttpServletResponse response); @RequestMapping(value = "/handle22") ModelAndView handle22(HttpServletRequest request); @RequestMapping(value = "/handle23") String handle23(HttpSession session); @RequestMapping(value = "/success") String success(); @RequestMapping(value = "/fail") String fail(); @RequestMapping(value = "/handle24") String handle24(HttpServletRequest request,
@RequestParam("userName") String userName); @RequestMapping(value = "/handle25") String handle25(WebRequest request); @RequestMapping(value = "/handle31") void handle31(OutputStream os); @RequestMapping(value = "/handle41") String handle41(@RequestBody String body); @ResponseBody @RequestMapping(value = "/handle42/{imageId}") byte[] handle42(@PathVariable("imageId") String imageId); @RequestMapping(value = "/handle43") String handle43(HttpEntity<String> requestEntity); @RequestMapping(value = "/handle44/{imageId}") ResponseEntity<byte[]> handle44(
@PathVariable("imageId") String imageId); @RequestMapping(value = "/handle51") ResponseEntity<User> handle51(HttpEntity<User> requestEntity); @RequestMapping(value = "/handle61") String handle61(@ModelAttribute("user") User user); @RequestMapping(value = "/handle62") String handle62(@ModelAttribute("user") User user); @RequestMapping(value = "/handle63") String handle63(ModelMap modelMap); @ModelAttribute("user") User getUser(); @ModelAttribute("user1") User getUser1(); @ModelAttribute("user2") User getUser2(); @ModelAttribute("dept") Dept getDept(); @RequestMapping(value = "/handle71") String handle71(@ModelAttribute("user") User user); @RequestMapping(value = "/handle72") String handle72(ModelMap modelMap, SessionStatus sessionStatus); @RequestMapping(value = "/handle81") String handle81(@RequestParam("user") User user, ModelMap modelMap); @RequestMapping(value = "/register2") String register2(User user); @RequestMapping(value = "/handle82") String handle82(User user); @RequestMapping(value = "/register3") String register3(); @RequestMapping(value = "/register4") String register4(); @RequestMapping(value = "/handle91") String handle91(@Valid @ModelAttribute("user") User user,
BindingResult bindingResult, ModelMap mm); @RequestMapping(value = "/handle92") String handle92(@ModelAttribute("user") User user,
BindingResult bindingResult); @RequestMapping(value = "/welcome") String handle100(); @RequestMapping(value = "/showUserList") String showUserList(ModelMap mm); @RequestMapping(value = "/showUserListByFtl") String showUserListInFtl(ModelMap mm); @RequestMapping(value = "/showUserListByXls") String showUserListInExcel(ModelMap mm); @RequestMapping(value = "/showUserListByPdf") String showUserListInPdf(ModelMap mm); @RequestMapping(value = "/showUserListByXml") String showUserListInXml(ModelMap mm); @RequestMapping(value = "/showUserListByJson") String showUserListInJson(ModelMap mm); @RequestMapping(value = "/showUserListByJson1") String showUserListInJson1(ModelMap mm); @RequestMapping(value = "/showUserListByI18n") String showUserListInI18n(ModelMap mm); @RequestMapping(value = "/showUserListMix") String showUserListMix(ModelMap mm); @RequestMapping(value = "/uploadPage") String updatePage(); @RequestMapping(value = "/upload") String updateThumb(@RequestParam("name") String name,
@RequestParam("file") MultipartFile file); @RequestMapping(value = "/throwException") String throwException(); @ExceptionHandler(RuntimeException.class) String handleException(RuntimeException re, HttpServletRequest request); @RequestMapping(value = "/notFound") String notFound(); @ResponseStatus(HttpStatus.NOT_FOUND) String notFound(HttpServletRequest request); @InitBinder void initBinder(WebDataBinder binder); }
|
@Test public void testhandle61() { RestTemplate restTemplate = new RestTemplate(); MultiValueMap<String, String> form = new LinkedMultiValueMap<String, String>(); form.add("userName", "tom"); form.add("password", "123456"); form.add("age", "45"); String html = restTemplate.postForObject( "http: Assert.assertNotNull(html); Assert.assertTrue(html.indexOf("1000") > -1); }
|
UserController { @RequestMapping(value = "/handle62") public String handle62(@ModelAttribute("user") User user) { user.setUserName("tom"); return "/user/showUser"; } @Autowired void setUserService(UserService userService); @RequestMapping(method = RequestMethod.POST) ModelAndView createUser(User user); @RequestMapping(value = "/register", method = RequestMethod.GET, params = "!myParam") String register(@ModelAttribute("user") User user); @RequestMapping(value = "/delete", method = RequestMethod.POST, params = "userId") String test1(@RequestParam("userId") String userId); @RequestMapping(value = "/show", headers = "content-type=text/*") String test2(@RequestParam("userId") String userId); @RequestMapping(value = "/handle1") String handle1(@RequestParam("userName") String userName,
@RequestParam("password") String password,
@RequestParam("realName") String realName); @RequestMapping(value = "/handle2") ModelAndView handle2(@CookieValue("JSESSIONID") String sessionId,
@RequestHeader("Accept-Language") String accpetLanguage); @RequestMapping(value = "/handle3") String handle3(User user); @RequestMapping(value = "/handle4") String handle4(HttpServletRequest request); @RequestMapping(value = "/handle11") String handle11(
@RequestParam(value = "userName", required = false) String userName,
@RequestParam("age") int age); @RequestMapping(value = "/handle12") String handle12(
@CookieValue(value = "sessionId", required = false) String sessionId,
@RequestParam("age") int age); @RequestMapping(value = "/handle13") String handle13(@RequestHeader("Accept-Encoding") String encoding,
@RequestHeader("Keep-Alive") long keepAlive); @RequestMapping(value = "/handle14") String handle14(User user); @RequestMapping(value = "/handle21") void handle21(HttpServletRequest request,
HttpServletResponse response); @RequestMapping(value = "/handle22") ModelAndView handle22(HttpServletRequest request); @RequestMapping(value = "/handle23") String handle23(HttpSession session); @RequestMapping(value = "/success") String success(); @RequestMapping(value = "/fail") String fail(); @RequestMapping(value = "/handle24") String handle24(HttpServletRequest request,
@RequestParam("userName") String userName); @RequestMapping(value = "/handle25") String handle25(WebRequest request); @RequestMapping(value = "/handle31") void handle31(OutputStream os); @RequestMapping(value = "/handle41") String handle41(@RequestBody String body); @ResponseBody @RequestMapping(value = "/handle42/{imageId}") byte[] handle42(@PathVariable("imageId") String imageId); @RequestMapping(value = "/handle43") String handle43(HttpEntity<String> requestEntity); @RequestMapping(value = "/handle44/{imageId}") ResponseEntity<byte[]> handle44(
@PathVariable("imageId") String imageId); @RequestMapping(value = "/handle51") ResponseEntity<User> handle51(HttpEntity<User> requestEntity); @RequestMapping(value = "/handle61") String handle61(@ModelAttribute("user") User user); @RequestMapping(value = "/handle62") String handle62(@ModelAttribute("user") User user); @RequestMapping(value = "/handle63") String handle63(ModelMap modelMap); @ModelAttribute("user") User getUser(); @ModelAttribute("user1") User getUser1(); @ModelAttribute("user2") User getUser2(); @ModelAttribute("dept") Dept getDept(); @RequestMapping(value = "/handle71") String handle71(@ModelAttribute("user") User user); @RequestMapping(value = "/handle72") String handle72(ModelMap modelMap, SessionStatus sessionStatus); @RequestMapping(value = "/handle81") String handle81(@RequestParam("user") User user, ModelMap modelMap); @RequestMapping(value = "/register2") String register2(User user); @RequestMapping(value = "/handle82") String handle82(User user); @RequestMapping(value = "/register3") String register3(); @RequestMapping(value = "/register4") String register4(); @RequestMapping(value = "/handle91") String handle91(@Valid @ModelAttribute("user") User user,
BindingResult bindingResult, ModelMap mm); @RequestMapping(value = "/handle92") String handle92(@ModelAttribute("user") User user,
BindingResult bindingResult); @RequestMapping(value = "/welcome") String handle100(); @RequestMapping(value = "/showUserList") String showUserList(ModelMap mm); @RequestMapping(value = "/showUserListByFtl") String showUserListInFtl(ModelMap mm); @RequestMapping(value = "/showUserListByXls") String showUserListInExcel(ModelMap mm); @RequestMapping(value = "/showUserListByPdf") String showUserListInPdf(ModelMap mm); @RequestMapping(value = "/showUserListByXml") String showUserListInXml(ModelMap mm); @RequestMapping(value = "/showUserListByJson") String showUserListInJson(ModelMap mm); @RequestMapping(value = "/showUserListByJson1") String showUserListInJson1(ModelMap mm); @RequestMapping(value = "/showUserListByI18n") String showUserListInI18n(ModelMap mm); @RequestMapping(value = "/showUserListMix") String showUserListMix(ModelMap mm); @RequestMapping(value = "/uploadPage") String updatePage(); @RequestMapping(value = "/upload") String updateThumb(@RequestParam("name") String name,
@RequestParam("file") MultipartFile file); @RequestMapping(value = "/throwException") String throwException(); @ExceptionHandler(RuntimeException.class) String handleException(RuntimeException re, HttpServletRequest request); @RequestMapping(value = "/notFound") String notFound(); @ResponseStatus(HttpStatus.NOT_FOUND) String notFound(HttpServletRequest request); @InitBinder void initBinder(WebDataBinder binder); }
|
@Test public void testhandle62() { RestTemplate restTemplate = new RestTemplate(); String html = restTemplate.postForObject( "http: Assert.assertNotNull(html); Assert.assertTrue(html.indexOf("1001") > -1); }
|
UserController { @RequestMapping(value = "/handle63") public String handle63(ModelMap modelMap) { User user = (User) modelMap.get("user"); user.setUserName("tom"); modelMap.addAttribute("testAttr", "value1"); return "/user/showUser"; } @Autowired void setUserService(UserService userService); @RequestMapping(method = RequestMethod.POST) ModelAndView createUser(User user); @RequestMapping(value = "/register", method = RequestMethod.GET, params = "!myParam") String register(@ModelAttribute("user") User user); @RequestMapping(value = "/delete", method = RequestMethod.POST, params = "userId") String test1(@RequestParam("userId") String userId); @RequestMapping(value = "/show", headers = "content-type=text/*") String test2(@RequestParam("userId") String userId); @RequestMapping(value = "/handle1") String handle1(@RequestParam("userName") String userName,
@RequestParam("password") String password,
@RequestParam("realName") String realName); @RequestMapping(value = "/handle2") ModelAndView handle2(@CookieValue("JSESSIONID") String sessionId,
@RequestHeader("Accept-Language") String accpetLanguage); @RequestMapping(value = "/handle3") String handle3(User user); @RequestMapping(value = "/handle4") String handle4(HttpServletRequest request); @RequestMapping(value = "/handle11") String handle11(
@RequestParam(value = "userName", required = false) String userName,
@RequestParam("age") int age); @RequestMapping(value = "/handle12") String handle12(
@CookieValue(value = "sessionId", required = false) String sessionId,
@RequestParam("age") int age); @RequestMapping(value = "/handle13") String handle13(@RequestHeader("Accept-Encoding") String encoding,
@RequestHeader("Keep-Alive") long keepAlive); @RequestMapping(value = "/handle14") String handle14(User user); @RequestMapping(value = "/handle21") void handle21(HttpServletRequest request,
HttpServletResponse response); @RequestMapping(value = "/handle22") ModelAndView handle22(HttpServletRequest request); @RequestMapping(value = "/handle23") String handle23(HttpSession session); @RequestMapping(value = "/success") String success(); @RequestMapping(value = "/fail") String fail(); @RequestMapping(value = "/handle24") String handle24(HttpServletRequest request,
@RequestParam("userName") String userName); @RequestMapping(value = "/handle25") String handle25(WebRequest request); @RequestMapping(value = "/handle31") void handle31(OutputStream os); @RequestMapping(value = "/handle41") String handle41(@RequestBody String body); @ResponseBody @RequestMapping(value = "/handle42/{imageId}") byte[] handle42(@PathVariable("imageId") String imageId); @RequestMapping(value = "/handle43") String handle43(HttpEntity<String> requestEntity); @RequestMapping(value = "/handle44/{imageId}") ResponseEntity<byte[]> handle44(
@PathVariable("imageId") String imageId); @RequestMapping(value = "/handle51") ResponseEntity<User> handle51(HttpEntity<User> requestEntity); @RequestMapping(value = "/handle61") String handle61(@ModelAttribute("user") User user); @RequestMapping(value = "/handle62") String handle62(@ModelAttribute("user") User user); @RequestMapping(value = "/handle63") String handle63(ModelMap modelMap); @ModelAttribute("user") User getUser(); @ModelAttribute("user1") User getUser1(); @ModelAttribute("user2") User getUser2(); @ModelAttribute("dept") Dept getDept(); @RequestMapping(value = "/handle71") String handle71(@ModelAttribute("user") User user); @RequestMapping(value = "/handle72") String handle72(ModelMap modelMap, SessionStatus sessionStatus); @RequestMapping(value = "/handle81") String handle81(@RequestParam("user") User user, ModelMap modelMap); @RequestMapping(value = "/register2") String register2(User user); @RequestMapping(value = "/handle82") String handle82(User user); @RequestMapping(value = "/register3") String register3(); @RequestMapping(value = "/register4") String register4(); @RequestMapping(value = "/handle91") String handle91(@Valid @ModelAttribute("user") User user,
BindingResult bindingResult, ModelMap mm); @RequestMapping(value = "/handle92") String handle92(@ModelAttribute("user") User user,
BindingResult bindingResult); @RequestMapping(value = "/welcome") String handle100(); @RequestMapping(value = "/showUserList") String showUserList(ModelMap mm); @RequestMapping(value = "/showUserListByFtl") String showUserListInFtl(ModelMap mm); @RequestMapping(value = "/showUserListByXls") String showUserListInExcel(ModelMap mm); @RequestMapping(value = "/showUserListByPdf") String showUserListInPdf(ModelMap mm); @RequestMapping(value = "/showUserListByXml") String showUserListInXml(ModelMap mm); @RequestMapping(value = "/showUserListByJson") String showUserListInJson(ModelMap mm); @RequestMapping(value = "/showUserListByJson1") String showUserListInJson1(ModelMap mm); @RequestMapping(value = "/showUserListByI18n") String showUserListInI18n(ModelMap mm); @RequestMapping(value = "/showUserListMix") String showUserListMix(ModelMap mm); @RequestMapping(value = "/uploadPage") String updatePage(); @RequestMapping(value = "/upload") String updateThumb(@RequestParam("name") String name,
@RequestParam("file") MultipartFile file); @RequestMapping(value = "/throwException") String throwException(); @ExceptionHandler(RuntimeException.class) String handleException(RuntimeException re, HttpServletRequest request); @RequestMapping(value = "/notFound") String notFound(); @ResponseStatus(HttpStatus.NOT_FOUND) String notFound(HttpServletRequest request); @InitBinder void initBinder(WebDataBinder binder); }
|
@Test public void testhandle63() { RestTemplate restTemplate = new RestTemplate(); String html = restTemplate.postForObject( "http: Assert.assertNotNull(html); Assert.assertTrue(html.indexOf("1001") > -1); }
|
UserController { @RequestMapping(value = "/handle71") public String handle71(@ModelAttribute("user") User user) { user.setUserName("John"); return "redirect:handle72.html"; } @Autowired void setUserService(UserService userService); @RequestMapping(method = RequestMethod.POST) ModelAndView createUser(User user); @RequestMapping(value = "/register", method = RequestMethod.GET, params = "!myParam") String register(@ModelAttribute("user") User user); @RequestMapping(value = "/delete", method = RequestMethod.POST, params = "userId") String test1(@RequestParam("userId") String userId); @RequestMapping(value = "/show", headers = "content-type=text/*") String test2(@RequestParam("userId") String userId); @RequestMapping(value = "/handle1") String handle1(@RequestParam("userName") String userName,
@RequestParam("password") String password,
@RequestParam("realName") String realName); @RequestMapping(value = "/handle2") ModelAndView handle2(@CookieValue("JSESSIONID") String sessionId,
@RequestHeader("Accept-Language") String accpetLanguage); @RequestMapping(value = "/handle3") String handle3(User user); @RequestMapping(value = "/handle4") String handle4(HttpServletRequest request); @RequestMapping(value = "/handle11") String handle11(
@RequestParam(value = "userName", required = false) String userName,
@RequestParam("age") int age); @RequestMapping(value = "/handle12") String handle12(
@CookieValue(value = "sessionId", required = false) String sessionId,
@RequestParam("age") int age); @RequestMapping(value = "/handle13") String handle13(@RequestHeader("Accept-Encoding") String encoding,
@RequestHeader("Keep-Alive") long keepAlive); @RequestMapping(value = "/handle14") String handle14(User user); @RequestMapping(value = "/handle21") void handle21(HttpServletRequest request,
HttpServletResponse response); @RequestMapping(value = "/handle22") ModelAndView handle22(HttpServletRequest request); @RequestMapping(value = "/handle23") String handle23(HttpSession session); @RequestMapping(value = "/success") String success(); @RequestMapping(value = "/fail") String fail(); @RequestMapping(value = "/handle24") String handle24(HttpServletRequest request,
@RequestParam("userName") String userName); @RequestMapping(value = "/handle25") String handle25(WebRequest request); @RequestMapping(value = "/handle31") void handle31(OutputStream os); @RequestMapping(value = "/handle41") String handle41(@RequestBody String body); @ResponseBody @RequestMapping(value = "/handle42/{imageId}") byte[] handle42(@PathVariable("imageId") String imageId); @RequestMapping(value = "/handle43") String handle43(HttpEntity<String> requestEntity); @RequestMapping(value = "/handle44/{imageId}") ResponseEntity<byte[]> handle44(
@PathVariable("imageId") String imageId); @RequestMapping(value = "/handle51") ResponseEntity<User> handle51(HttpEntity<User> requestEntity); @RequestMapping(value = "/handle61") String handle61(@ModelAttribute("user") User user); @RequestMapping(value = "/handle62") String handle62(@ModelAttribute("user") User user); @RequestMapping(value = "/handle63") String handle63(ModelMap modelMap); @ModelAttribute("user") User getUser(); @ModelAttribute("user1") User getUser1(); @ModelAttribute("user2") User getUser2(); @ModelAttribute("dept") Dept getDept(); @RequestMapping(value = "/handle71") String handle71(@ModelAttribute("user") User user); @RequestMapping(value = "/handle72") String handle72(ModelMap modelMap, SessionStatus sessionStatus); @RequestMapping(value = "/handle81") String handle81(@RequestParam("user") User user, ModelMap modelMap); @RequestMapping(value = "/register2") String register2(User user); @RequestMapping(value = "/handle82") String handle82(User user); @RequestMapping(value = "/register3") String register3(); @RequestMapping(value = "/register4") String register4(); @RequestMapping(value = "/handle91") String handle91(@Valid @ModelAttribute("user") User user,
BindingResult bindingResult, ModelMap mm); @RequestMapping(value = "/handle92") String handle92(@ModelAttribute("user") User user,
BindingResult bindingResult); @RequestMapping(value = "/welcome") String handle100(); @RequestMapping(value = "/showUserList") String showUserList(ModelMap mm); @RequestMapping(value = "/showUserListByFtl") String showUserListInFtl(ModelMap mm); @RequestMapping(value = "/showUserListByXls") String showUserListInExcel(ModelMap mm); @RequestMapping(value = "/showUserListByPdf") String showUserListInPdf(ModelMap mm); @RequestMapping(value = "/showUserListByXml") String showUserListInXml(ModelMap mm); @RequestMapping(value = "/showUserListByJson") String showUserListInJson(ModelMap mm); @RequestMapping(value = "/showUserListByJson1") String showUserListInJson1(ModelMap mm); @RequestMapping(value = "/showUserListByI18n") String showUserListInI18n(ModelMap mm); @RequestMapping(value = "/showUserListMix") String showUserListMix(ModelMap mm); @RequestMapping(value = "/uploadPage") String updatePage(); @RequestMapping(value = "/upload") String updateThumb(@RequestParam("name") String name,
@RequestParam("file") MultipartFile file); @RequestMapping(value = "/throwException") String throwException(); @ExceptionHandler(RuntimeException.class) String handleException(RuntimeException re, HttpServletRequest request); @RequestMapping(value = "/notFound") String notFound(); @ResponseStatus(HttpStatus.NOT_FOUND) String notFound(HttpServletRequest request); @InitBinder void initBinder(WebDataBinder binder); }
|
@Test public void testhandle71() { RestTemplate restTemplate = new RestTemplate(); MultiValueMap<String, String> form = new LinkedMultiValueMap<String, String>(); form.add("userName", "tom"); form.add("password", "123456"); form.add("age", "45"); restTemplate.postForLocation("http: }
|
UserController { @RequestMapping(value = "/handle81") public String handle81(@RequestParam("user") User user, ModelMap modelMap) { modelMap.put("user", user); return "/user/showUser"; } @Autowired void setUserService(UserService userService); @RequestMapping(method = RequestMethod.POST) ModelAndView createUser(User user); @RequestMapping(value = "/register", method = RequestMethod.GET, params = "!myParam") String register(@ModelAttribute("user") User user); @RequestMapping(value = "/delete", method = RequestMethod.POST, params = "userId") String test1(@RequestParam("userId") String userId); @RequestMapping(value = "/show", headers = "content-type=text/*") String test2(@RequestParam("userId") String userId); @RequestMapping(value = "/handle1") String handle1(@RequestParam("userName") String userName,
@RequestParam("password") String password,
@RequestParam("realName") String realName); @RequestMapping(value = "/handle2") ModelAndView handle2(@CookieValue("JSESSIONID") String sessionId,
@RequestHeader("Accept-Language") String accpetLanguage); @RequestMapping(value = "/handle3") String handle3(User user); @RequestMapping(value = "/handle4") String handle4(HttpServletRequest request); @RequestMapping(value = "/handle11") String handle11(
@RequestParam(value = "userName", required = false) String userName,
@RequestParam("age") int age); @RequestMapping(value = "/handle12") String handle12(
@CookieValue(value = "sessionId", required = false) String sessionId,
@RequestParam("age") int age); @RequestMapping(value = "/handle13") String handle13(@RequestHeader("Accept-Encoding") String encoding,
@RequestHeader("Keep-Alive") long keepAlive); @RequestMapping(value = "/handle14") String handle14(User user); @RequestMapping(value = "/handle21") void handle21(HttpServletRequest request,
HttpServletResponse response); @RequestMapping(value = "/handle22") ModelAndView handle22(HttpServletRequest request); @RequestMapping(value = "/handle23") String handle23(HttpSession session); @RequestMapping(value = "/success") String success(); @RequestMapping(value = "/fail") String fail(); @RequestMapping(value = "/handle24") String handle24(HttpServletRequest request,
@RequestParam("userName") String userName); @RequestMapping(value = "/handle25") String handle25(WebRequest request); @RequestMapping(value = "/handle31") void handle31(OutputStream os); @RequestMapping(value = "/handle41") String handle41(@RequestBody String body); @ResponseBody @RequestMapping(value = "/handle42/{imageId}") byte[] handle42(@PathVariable("imageId") String imageId); @RequestMapping(value = "/handle43") String handle43(HttpEntity<String> requestEntity); @RequestMapping(value = "/handle44/{imageId}") ResponseEntity<byte[]> handle44(
@PathVariable("imageId") String imageId); @RequestMapping(value = "/handle51") ResponseEntity<User> handle51(HttpEntity<User> requestEntity); @RequestMapping(value = "/handle61") String handle61(@ModelAttribute("user") User user); @RequestMapping(value = "/handle62") String handle62(@ModelAttribute("user") User user); @RequestMapping(value = "/handle63") String handle63(ModelMap modelMap); @ModelAttribute("user") User getUser(); @ModelAttribute("user1") User getUser1(); @ModelAttribute("user2") User getUser2(); @ModelAttribute("dept") Dept getDept(); @RequestMapping(value = "/handle71") String handle71(@ModelAttribute("user") User user); @RequestMapping(value = "/handle72") String handle72(ModelMap modelMap, SessionStatus sessionStatus); @RequestMapping(value = "/handle81") String handle81(@RequestParam("user") User user, ModelMap modelMap); @RequestMapping(value = "/register2") String register2(User user); @RequestMapping(value = "/handle82") String handle82(User user); @RequestMapping(value = "/register3") String register3(); @RequestMapping(value = "/register4") String register4(); @RequestMapping(value = "/handle91") String handle91(@Valid @ModelAttribute("user") User user,
BindingResult bindingResult, ModelMap mm); @RequestMapping(value = "/handle92") String handle92(@ModelAttribute("user") User user,
BindingResult bindingResult); @RequestMapping(value = "/welcome") String handle100(); @RequestMapping(value = "/showUserList") String showUserList(ModelMap mm); @RequestMapping(value = "/showUserListByFtl") String showUserListInFtl(ModelMap mm); @RequestMapping(value = "/showUserListByXls") String showUserListInExcel(ModelMap mm); @RequestMapping(value = "/showUserListByPdf") String showUserListInPdf(ModelMap mm); @RequestMapping(value = "/showUserListByXml") String showUserListInXml(ModelMap mm); @RequestMapping(value = "/showUserListByJson") String showUserListInJson(ModelMap mm); @RequestMapping(value = "/showUserListByJson1") String showUserListInJson1(ModelMap mm); @RequestMapping(value = "/showUserListByI18n") String showUserListInI18n(ModelMap mm); @RequestMapping(value = "/showUserListMix") String showUserListMix(ModelMap mm); @RequestMapping(value = "/uploadPage") String updatePage(); @RequestMapping(value = "/upload") String updateThumb(@RequestParam("name") String name,
@RequestParam("file") MultipartFile file); @RequestMapping(value = "/throwException") String throwException(); @ExceptionHandler(RuntimeException.class) String handleException(RuntimeException re, HttpServletRequest request); @RequestMapping(value = "/notFound") String notFound(); @ResponseStatus(HttpStatus.NOT_FOUND) String notFound(HttpServletRequest request); @InitBinder void initBinder(WebDataBinder binder); }
|
@Test public void testhandle81() { RestTemplate restTemplate = new RestTemplate(); MultiValueMap<String, String> form = new LinkedMultiValueMap<String, String>(); form.add("user", "tom:123456:tomson"); String html = restTemplate.postForObject( "http: Assert.assertNotNull(html); Assert.assertTrue(html.indexOf("tom") > -1); }
|
UserController { @RequestMapping(value = "/handle82") public String handle82(User user) { return "/user/showUser"; } @Autowired void setUserService(UserService userService); @RequestMapping(method = RequestMethod.POST) ModelAndView createUser(User user); @RequestMapping(value = "/register", method = RequestMethod.GET, params = "!myParam") String register(@ModelAttribute("user") User user); @RequestMapping(value = "/delete", method = RequestMethod.POST, params = "userId") String test1(@RequestParam("userId") String userId); @RequestMapping(value = "/show", headers = "content-type=text/*") String test2(@RequestParam("userId") String userId); @RequestMapping(value = "/handle1") String handle1(@RequestParam("userName") String userName,
@RequestParam("password") String password,
@RequestParam("realName") String realName); @RequestMapping(value = "/handle2") ModelAndView handle2(@CookieValue("JSESSIONID") String sessionId,
@RequestHeader("Accept-Language") String accpetLanguage); @RequestMapping(value = "/handle3") String handle3(User user); @RequestMapping(value = "/handle4") String handle4(HttpServletRequest request); @RequestMapping(value = "/handle11") String handle11(
@RequestParam(value = "userName", required = false) String userName,
@RequestParam("age") int age); @RequestMapping(value = "/handle12") String handle12(
@CookieValue(value = "sessionId", required = false) String sessionId,
@RequestParam("age") int age); @RequestMapping(value = "/handle13") String handle13(@RequestHeader("Accept-Encoding") String encoding,
@RequestHeader("Keep-Alive") long keepAlive); @RequestMapping(value = "/handle14") String handle14(User user); @RequestMapping(value = "/handle21") void handle21(HttpServletRequest request,
HttpServletResponse response); @RequestMapping(value = "/handle22") ModelAndView handle22(HttpServletRequest request); @RequestMapping(value = "/handle23") String handle23(HttpSession session); @RequestMapping(value = "/success") String success(); @RequestMapping(value = "/fail") String fail(); @RequestMapping(value = "/handle24") String handle24(HttpServletRequest request,
@RequestParam("userName") String userName); @RequestMapping(value = "/handle25") String handle25(WebRequest request); @RequestMapping(value = "/handle31") void handle31(OutputStream os); @RequestMapping(value = "/handle41") String handle41(@RequestBody String body); @ResponseBody @RequestMapping(value = "/handle42/{imageId}") byte[] handle42(@PathVariable("imageId") String imageId); @RequestMapping(value = "/handle43") String handle43(HttpEntity<String> requestEntity); @RequestMapping(value = "/handle44/{imageId}") ResponseEntity<byte[]> handle44(
@PathVariable("imageId") String imageId); @RequestMapping(value = "/handle51") ResponseEntity<User> handle51(HttpEntity<User> requestEntity); @RequestMapping(value = "/handle61") String handle61(@ModelAttribute("user") User user); @RequestMapping(value = "/handle62") String handle62(@ModelAttribute("user") User user); @RequestMapping(value = "/handle63") String handle63(ModelMap modelMap); @ModelAttribute("user") User getUser(); @ModelAttribute("user1") User getUser1(); @ModelAttribute("user2") User getUser2(); @ModelAttribute("dept") Dept getDept(); @RequestMapping(value = "/handle71") String handle71(@ModelAttribute("user") User user); @RequestMapping(value = "/handle72") String handle72(ModelMap modelMap, SessionStatus sessionStatus); @RequestMapping(value = "/handle81") String handle81(@RequestParam("user") User user, ModelMap modelMap); @RequestMapping(value = "/register2") String register2(User user); @RequestMapping(value = "/handle82") String handle82(User user); @RequestMapping(value = "/register3") String register3(); @RequestMapping(value = "/register4") String register4(); @RequestMapping(value = "/handle91") String handle91(@Valid @ModelAttribute("user") User user,
BindingResult bindingResult, ModelMap mm); @RequestMapping(value = "/handle92") String handle92(@ModelAttribute("user") User user,
BindingResult bindingResult); @RequestMapping(value = "/welcome") String handle100(); @RequestMapping(value = "/showUserList") String showUserList(ModelMap mm); @RequestMapping(value = "/showUserListByFtl") String showUserListInFtl(ModelMap mm); @RequestMapping(value = "/showUserListByXls") String showUserListInExcel(ModelMap mm); @RequestMapping(value = "/showUserListByPdf") String showUserListInPdf(ModelMap mm); @RequestMapping(value = "/showUserListByXml") String showUserListInXml(ModelMap mm); @RequestMapping(value = "/showUserListByJson") String showUserListInJson(ModelMap mm); @RequestMapping(value = "/showUserListByJson1") String showUserListInJson1(ModelMap mm); @RequestMapping(value = "/showUserListByI18n") String showUserListInI18n(ModelMap mm); @RequestMapping(value = "/showUserListMix") String showUserListMix(ModelMap mm); @RequestMapping(value = "/uploadPage") String updatePage(); @RequestMapping(value = "/upload") String updateThumb(@RequestParam("name") String name,
@RequestParam("file") MultipartFile file); @RequestMapping(value = "/throwException") String throwException(); @ExceptionHandler(RuntimeException.class) String handleException(RuntimeException re, HttpServletRequest request); @RequestMapping(value = "/notFound") String notFound(); @ResponseStatus(HttpStatus.NOT_FOUND) String notFound(HttpServletRequest request); @InitBinder void initBinder(WebDataBinder binder); }
|
@Test public void testhandle82() { RestTemplate restTemplate = new RestTemplate(); MultiValueMap<String, String> form = new LinkedMultiValueMap<String, String>(); form.add("userName", "tom"); form.add("password", "123456"); form.add("age", "45"); form.add("birthday", "1980-01-01"); form.add("salary", "4,500.00"); String html = restTemplate.postForObject( "http: Assert.assertNotNull(html); Assert.assertTrue(html.indexOf("tom") > -1); }
|
UserController { @RequestMapping(value = "/handle91") public String handle91(@Valid @ModelAttribute("user") User user, BindingResult bindingResult, ModelMap mm) { if (bindingResult.hasErrors()) { return "/user/register3"; } else { return "/user/showUser"; } } @Autowired void setUserService(UserService userService); @RequestMapping(method = RequestMethod.POST) ModelAndView createUser(User user); @RequestMapping(value = "/register", method = RequestMethod.GET, params = "!myParam") String register(@ModelAttribute("user") User user); @RequestMapping(value = "/delete", method = RequestMethod.POST, params = "userId") String test1(@RequestParam("userId") String userId); @RequestMapping(value = "/show", headers = "content-type=text/*") String test2(@RequestParam("userId") String userId); @RequestMapping(value = "/handle1") String handle1(@RequestParam("userName") String userName,
@RequestParam("password") String password,
@RequestParam("realName") String realName); @RequestMapping(value = "/handle2") ModelAndView handle2(@CookieValue("JSESSIONID") String sessionId,
@RequestHeader("Accept-Language") String accpetLanguage); @RequestMapping(value = "/handle3") String handle3(User user); @RequestMapping(value = "/handle4") String handle4(HttpServletRequest request); @RequestMapping(value = "/handle11") String handle11(
@RequestParam(value = "userName", required = false) String userName,
@RequestParam("age") int age); @RequestMapping(value = "/handle12") String handle12(
@CookieValue(value = "sessionId", required = false) String sessionId,
@RequestParam("age") int age); @RequestMapping(value = "/handle13") String handle13(@RequestHeader("Accept-Encoding") String encoding,
@RequestHeader("Keep-Alive") long keepAlive); @RequestMapping(value = "/handle14") String handle14(User user); @RequestMapping(value = "/handle21") void handle21(HttpServletRequest request,
HttpServletResponse response); @RequestMapping(value = "/handle22") ModelAndView handle22(HttpServletRequest request); @RequestMapping(value = "/handle23") String handle23(HttpSession session); @RequestMapping(value = "/success") String success(); @RequestMapping(value = "/fail") String fail(); @RequestMapping(value = "/handle24") String handle24(HttpServletRequest request,
@RequestParam("userName") String userName); @RequestMapping(value = "/handle25") String handle25(WebRequest request); @RequestMapping(value = "/handle31") void handle31(OutputStream os); @RequestMapping(value = "/handle41") String handle41(@RequestBody String body); @ResponseBody @RequestMapping(value = "/handle42/{imageId}") byte[] handle42(@PathVariable("imageId") String imageId); @RequestMapping(value = "/handle43") String handle43(HttpEntity<String> requestEntity); @RequestMapping(value = "/handle44/{imageId}") ResponseEntity<byte[]> handle44(
@PathVariable("imageId") String imageId); @RequestMapping(value = "/handle51") ResponseEntity<User> handle51(HttpEntity<User> requestEntity); @RequestMapping(value = "/handle61") String handle61(@ModelAttribute("user") User user); @RequestMapping(value = "/handle62") String handle62(@ModelAttribute("user") User user); @RequestMapping(value = "/handle63") String handle63(ModelMap modelMap); @ModelAttribute("user") User getUser(); @ModelAttribute("user1") User getUser1(); @ModelAttribute("user2") User getUser2(); @ModelAttribute("dept") Dept getDept(); @RequestMapping(value = "/handle71") String handle71(@ModelAttribute("user") User user); @RequestMapping(value = "/handle72") String handle72(ModelMap modelMap, SessionStatus sessionStatus); @RequestMapping(value = "/handle81") String handle81(@RequestParam("user") User user, ModelMap modelMap); @RequestMapping(value = "/register2") String register2(User user); @RequestMapping(value = "/handle82") String handle82(User user); @RequestMapping(value = "/register3") String register3(); @RequestMapping(value = "/register4") String register4(); @RequestMapping(value = "/handle91") String handle91(@Valid @ModelAttribute("user") User user,
BindingResult bindingResult, ModelMap mm); @RequestMapping(value = "/handle92") String handle92(@ModelAttribute("user") User user,
BindingResult bindingResult); @RequestMapping(value = "/welcome") String handle100(); @RequestMapping(value = "/showUserList") String showUserList(ModelMap mm); @RequestMapping(value = "/showUserListByFtl") String showUserListInFtl(ModelMap mm); @RequestMapping(value = "/showUserListByXls") String showUserListInExcel(ModelMap mm); @RequestMapping(value = "/showUserListByPdf") String showUserListInPdf(ModelMap mm); @RequestMapping(value = "/showUserListByXml") String showUserListInXml(ModelMap mm); @RequestMapping(value = "/showUserListByJson") String showUserListInJson(ModelMap mm); @RequestMapping(value = "/showUserListByJson1") String showUserListInJson1(ModelMap mm); @RequestMapping(value = "/showUserListByI18n") String showUserListInI18n(ModelMap mm); @RequestMapping(value = "/showUserListMix") String showUserListMix(ModelMap mm); @RequestMapping(value = "/uploadPage") String updatePage(); @RequestMapping(value = "/upload") String updateThumb(@RequestParam("name") String name,
@RequestParam("file") MultipartFile file); @RequestMapping(value = "/throwException") String throwException(); @ExceptionHandler(RuntimeException.class) String handleException(RuntimeException re, HttpServletRequest request); @RequestMapping(value = "/notFound") String notFound(); @ResponseStatus(HttpStatus.NOT_FOUND) String notFound(HttpServletRequest request); @InitBinder void initBinder(WebDataBinder binder); }
|
@Test public void testhandle91() { RestTemplate restTemplate = new RestTemplate(); MultiValueMap<String, String> form = new LinkedMultiValueMap<String, String>(); form.add("userName", "tom"); form.add("password", "12345"); form.add("birthday", "1980-01-01"); form.add("salary", "4,500.00"); String html = restTemplate.postForObject( "http: Assert.assertNotNull(html); Assert.assertTrue(html.indexOf("tom") > -1); }
|
ForumService { public void addBoard(Board board) { boardDao.save(board); } @Autowired void setTopicDao(TopicDao topicDao); @Autowired void setUserDao(UserDao userDao); @Autowired void setBoardDao(BoardDao boardDao); @Autowired void setPostDao(PostDao postDao); void addTopic(Topic topic); void removeTopic(int topicId); void addPost(Post post); void removePost(int postId); void addBoard(Board board); void removeBoard(int boardId); void makeDigestTopic(int topicId); List<Board> getAllBoards(); Page getPagedTopics(int boardId,int pageNo,int pageSize); Page getPagedPosts(int topicId,int pageNo,int pageSize); Page queryTopicByTitle(String title,int pageNo,int pageSize); Board getBoardById(int boardId); Topic getTopicByTopicId(int topicId); Post getPostByPostId(int postId); void addBoardManager(int boardId,String userName); void updateTopic(Topic topic); void updatePost(Post post); }
|
@Test @DataSet("XiaoChun.DataSet.xls") public void addBoard() throws Exception { Board board = XlsDataSetBeanFactory.createBean(ForumServiceTest.class, "XiaoChun.DataSet.xls", "t_board", Board.class); forumService.addBoard(board); Board boardDb = forumService.getBoardById(board.getBoardId()); assertEquals(boardDb.getBoardName(), equalTo("育儿")); }
|
ForumService { public void addTopic(Topic topic) { Board board = (Board) boardDao.get(topic.getBoardId()); board.setTopicNum(board.getTopicNum() + 1); topicDao.save(topic); topic.getMainPost().setTopic(topic); MainPost post = topic.getMainPost(); post.setCreateTime(new Date()); post.setUser(topic.getUser()); post.setPostTitle(topic.getTopicTitle()); post.setBoardId(topic.getBoardId()); postDao.save(topic.getMainPost()); User user = topic.getUser(); user.setCredit(user.getCredit() + 10); userDao.update(user); } @Autowired void setTopicDao(TopicDao topicDao); @Autowired void setUserDao(UserDao userDao); @Autowired void setBoardDao(BoardDao boardDao); @Autowired void setPostDao(PostDao postDao); void addTopic(Topic topic); void removeTopic(int topicId); void addPost(Post post); void removePost(int postId); void addBoard(Board board); void removeBoard(int boardId); void makeDigestTopic(int topicId); List<Board> getAllBoards(); Page getPagedTopics(int boardId,int pageNo,int pageSize); Page getPagedPosts(int topicId,int pageNo,int pageSize); Page queryTopicByTitle(String title,int pageNo,int pageSize); Board getBoardById(int boardId); Topic getTopicByTopicId(int topicId); Post getPostByPostId(int postId); void addBoardManager(int boardId,String userName); void updateTopic(Topic topic); void updatePost(Post post); }
|
@Test @DataSet("XiaoChun.DataSet.xls") public void addTopic() throws Exception { Topic topic = XlsDataSetBeanFactory.createBean(ForumServiceTest.class, "XiaoChun.DataSet.xls", "t_topic", Topic.class); User user = XlsDataSetBeanFactory.createBean(ForumServiceTest.class, "XiaoChun.DataSet.xls", "t_user", User.class); topic.setUser(user); forumService.addTopic(topic); Board boardDb = forumService.getBoardById(1); User userDb = userService.getUserByUserName("tom"); assertEquals(boardDb.getTopicNum(), is(1)); assertEquals(userDb.getCredit(), is(110)); assertEquals(topic.getTopicId(), greaterThan(0)); }
|
ForumService { public void removeTopic(int topicId) { Topic topic = topicDao.get(topicId); Board board = boardDao.get(topic.getBoardId()); board.setTopicNum(board.getTopicNum() - 1); User user = topic.getUser(); user.setCredit(user.getCredit() - 50); topicDao.remove(topic); postDao.deleteTopicPosts(topicId); } @Autowired void setTopicDao(TopicDao topicDao); @Autowired void setUserDao(UserDao userDao); @Autowired void setBoardDao(BoardDao boardDao); @Autowired void setPostDao(PostDao postDao); void addTopic(Topic topic); void removeTopic(int topicId); void addPost(Post post); void removePost(int postId); void addBoard(Board board); void removeBoard(int boardId); void makeDigestTopic(int topicId); List<Board> getAllBoards(); Page getPagedTopics(int boardId,int pageNo,int pageSize); Page getPagedPosts(int topicId,int pageNo,int pageSize); Page queryTopicByTitle(String title,int pageNo,int pageSize); Board getBoardById(int boardId); Topic getTopicByTopicId(int topicId); Post getPostByPostId(int postId); void addBoardManager(int boardId,String userName); void updateTopic(Topic topic); void updatePost(Post post); }
|
@Test @DataSet("XiaoChun.DataSet.xls") public void removeTopic() { forumService.removeTopic(1); Topic topicDb = forumService.getTopicByTopicId(1); assertNull(topicDb); }
|
ForumService { public void addPost(Post post){ postDao.save(post); User user = post.getUser(); user.setCredit(user.getCredit() + 5); userDao.update(user); Topic topic = topicDao.get(post.getTopic().getTopicId()); topic.setReplies(topic.getReplies() + 1); topic.setLastPost(new Date()); } @Autowired void setTopicDao(TopicDao topicDao); @Autowired void setUserDao(UserDao userDao); @Autowired void setBoardDao(BoardDao boardDao); @Autowired void setPostDao(PostDao postDao); void addTopic(Topic topic); void removeTopic(int topicId); void addPost(Post post); void removePost(int postId); void addBoard(Board board); void removeBoard(int boardId); void makeDigestTopic(int topicId); List<Board> getAllBoards(); Page getPagedTopics(int boardId,int pageNo,int pageSize); Page getPagedPosts(int topicId,int pageNo,int pageSize); Page queryTopicByTitle(String title,int pageNo,int pageSize); Board getBoardById(int boardId); Topic getTopicByTopicId(int topicId); Post getPostByPostId(int postId); void addBoardManager(int boardId,String userName); void updateTopic(Topic topic); void updatePost(Post post); }
|
@Test @DataSet("XiaoChun.DataSet.xls") public void addPost() throws Exception { Post post = XlsDataSetBeanFactory.createBean(ForumServiceTest.class, "XiaoChun.DataSet.xls", "t_post", Post.class); User user = XlsDataSetBeanFactory.createBean(ForumServiceTest.class, "XiaoChun.DataSet.xls", "t_user", User.class); Topic topic = new Topic(); topic.setTopicId(1); post.setUser(user); post.setTopic(topic); forumService.addPost(post); User userDb = userService.getUserByUserName("tom"); Topic topicDb = forumService.getTopicByTopicId(1); assertEquals(post.getPostId(), greaterThan(1)); assertEquals(userDb.getCredit(), equalTo(105)); assertEquals(topicDb.getReplies(), equalTo(2)); }
|
ForumService { public void removePost(int postId){ Post post = postDao.get(postId); postDao.remove(post); Topic topic = topicDao.get(post.getTopic().getTopicId()); topic.setReplies(topic.getReplies() - 1); User user =post.getUser(); user.setCredit(user.getCredit() - 20); } @Autowired void setTopicDao(TopicDao topicDao); @Autowired void setUserDao(UserDao userDao); @Autowired void setBoardDao(BoardDao boardDao); @Autowired void setPostDao(PostDao postDao); void addTopic(Topic topic); void removeTopic(int topicId); void addPost(Post post); void removePost(int postId); void addBoard(Board board); void removeBoard(int boardId); void makeDigestTopic(int topicId); List<Board> getAllBoards(); Page getPagedTopics(int boardId,int pageNo,int pageSize); Page getPagedPosts(int topicId,int pageNo,int pageSize); Page queryTopicByTitle(String title,int pageNo,int pageSize); Board getBoardById(int boardId); Topic getTopicByTopicId(int topicId); Post getPostByPostId(int postId); void addBoardManager(int boardId,String userName); void updateTopic(Topic topic); void updatePost(Post post); }
|
@Test @DataSet("XiaoChun.DataSet.xls") public void removePost() { forumService.removePost(1); Post postDb = forumService.getPostByPostId(1); User userDb = userService.getUserByUserName("tom"); Topic topicDb = forumService.getTopicByTopicId(1); assertNull(postDb); assertEquals(userDb.getCredit(), equalTo(80)); assertEquals(topicDb.getReplies(), equalTo(0)); }
|
ForumService { public void makeDigestTopic(int topicId){ Topic topic = topicDao.get(topicId); topic.setDigest(Topic.DIGEST_TOPIC); User user = topic.getUser(); user.setCredit(user.getCredit() + 100); } @Autowired void setTopicDao(TopicDao topicDao); @Autowired void setUserDao(UserDao userDao); @Autowired void setBoardDao(BoardDao boardDao); @Autowired void setPostDao(PostDao postDao); void addTopic(Topic topic); void removeTopic(int topicId); void addPost(Post post); void removePost(int postId); void addBoard(Board board); void removeBoard(int boardId); void makeDigestTopic(int topicId); List<Board> getAllBoards(); Page getPagedTopics(int boardId,int pageNo,int pageSize); Page getPagedPosts(int topicId,int pageNo,int pageSize); Page queryTopicByTitle(String title,int pageNo,int pageSize); Board getBoardById(int boardId); Topic getTopicByTopicId(int topicId); Post getPostByPostId(int postId); void addBoardManager(int boardId,String userName); void updateTopic(Topic topic); void updatePost(Post post); }
|
@Test @DataSet("XiaoChun.DataSet.xls") public void makeDigestTopic()throws Exception { forumService.makeDigestTopic(1); User userDb = userService.getUserByUserName("tom"); Topic topicDb = forumService.getTopicByTopicId(1); assertEquals(userDb.getCredit(), equalTo(200)); assertEquals(topicDb.getDigest(), equalTo(Topic.DIGEST_TOPIC)); }
|
JsonPatchListener implements DifferenceListener { public List<Difference> getDifferences() { return differences; } @Override void diff(final Difference difference, final DifferenceContext differenceContext); List<Difference> getDifferences(); DifferenceContext getContext(); DiffModel getDiffModel(); @SuppressWarnings({"all", "unchecked"}) String getJsonPatch(); }
|
@Test void shouldSeeEmptyDiffNodes() { Diff diff = Diff.create("{}", "{}", "", "", commonConfig()); diff.similar(); assertThat(listener.getDifferences()) .isEmpty(); }
|
JsonPatchListener implements DifferenceListener { @SuppressWarnings({"all", "unchecked"}) public String getJsonPatch() { final Map<String, Object> jsonDiffPatch = new HashMap<>(); if (getDifferences().size() == 1) { final Difference difference = getDifferences().get(0); final String field = getPath(difference); if (field.isEmpty()) { final ObjectMapper mapper = new ObjectMapper(); try { return mapper.writeValueAsString(getPatch(difference)); } catch (JsonProcessingException e) { throw new IllegalStateException("Could not process patch json", e); } } } getDifferences().forEach(difference -> { final String field = getPath(difference); Map<String, Object> currentMap = jsonDiffPatch; final String fieldWithDots = StringUtils.replace(field, "[", "."); final int len = fieldWithDots.length(); int left = 0; int right = 0; while (left < len) { right = fieldWithDots.indexOf('.', left); if (right == -1) { right = len; } String fieldName = fieldWithDots.substring(left, right); fieldName = StringUtils.remove(fieldName, "]"); if (right != len) { if (!fieldName.isEmpty()) { if (!currentMap.containsKey(fieldName)) { currentMap.put(fieldName, new HashMap<>()); } currentMap = (Map<String, Object>) currentMap.get(fieldName); } if (field.charAt(right) == '[') { if (!currentMap.containsKey(fieldName)) { currentMap.put("_t", "a"); } } } else { final List<?> actualExpectedValue = getPatch(difference); currentMap.put(fieldName, actualExpectedValue); } left = right + 1; } }); final ObjectMapper mapper = new ObjectMapper(); try { return mapper.writeValueAsString(jsonDiffPatch); } catch (JsonProcessingException e) { throw new IllegalStateException("Could not process patch json", e); } } @Override void diff(final Difference difference, final DifferenceContext differenceContext); List<Difference> getDifferences(); DifferenceContext getContext(); DiffModel getDiffModel(); @SuppressWarnings({"all", "unchecked"}) String getJsonPatch(); }
|
@Test void shouldSeeChangedStructureNode() { Diff diff = Diff.create("{\"test\": \"1\"}", "{\"test\": false}", "", "", commonConfig()); diff.similar(); assertThat(listener.getJsonPatch()).isEqualTo("{\"test\":[\"1\",false]}"); }
@Test void shouldSeeChangedArrayNode() { Diff diff = Diff.create("[1, 1]", "[1, 2]", "", "", commonConfig()); diff.similar(); assertThat(listener.getJsonPatch()).isEqualTo("{\"1\":[1,2],\"_t\":\"a\"}"); }
@Test void shouldSeeRemovedArrayNode() { Diff diff = Diff.create("[1, 2]", "[1]", "", "", commonConfig()); diff.similar(); assertThat(listener.getJsonPatch()).isEqualTo("{\"1\":[2,0,0],\"_t\":\"a\"}"); }
@Test void shouldSeeAddedArrayNode() { Diff diff = Diff.create("[1]", "[1, 2]", "", "", commonConfig()); diff.similar(); assertThat(listener.getJsonPatch()).isEqualTo("{\"1\":[2],\"_t\":\"a\"}"); }
@Test void shouldSeeObjectDiffNodes() { Diff diff = Diff.create("{\"test\": { \"test1\": \"1\"}}", "{\"test\": { \"test1\": \"2\"} }", "", "", commonConfig()); diff.similar(); assertThat(listener.getJsonPatch()).isEqualTo("{\"test\":{\"test1\":[\"1\",\"2\"]}}"); }
@Test void shouldSeeNullNode() { Diff diff = Diff.create(null, null, "", "", commonConfig()); diff.similar(); assertThat(listener.getJsonPatch()).isEqualTo("{}"); }
@Test void shouldWorkWhenIgnoringArrayOrder() { Diff diff = Diff.create("{\"test\": [[1,2],[2,3]]}", "{\"test\":[[4,2],[1,2]]}", "", "", commonConfig().when(Option.IGNORING_ARRAY_ORDER)); diff.similar(); assertThat(listener.getJsonPatch()). isEqualTo("{\"test\":{\"0\":{\"0\":[3,4],\"_t\":\"a\"},\"_t\":\"a\"}}"); }
@Test void shouldSeeNodeChangeToArray() { Diff diff = Diff.create("{\"test\": \"1\"}", "[[1,2],[2,3],[1,1]]", "", "", commonConfig()); diff.similar(); assertThat(listener.getJsonPatch()).isEqualTo("[{\"test\":\"1\"},[[1,2],[2,3],[1,1]]]"); }
@Test void shouldSeeRemovedNode() { Diff diff = Diff.create("{\"test\": \"1\"}", "{}", "", "", commonConfig()); diff.similar(); assertThat(listener.getJsonPatch()) .isEqualTo("{\"test\":[\"1\",0,0]}"); }
@Test void shouldArrayChangeToNode() { Diff diff = Diff.create("[[1,2],[2,3],[1,1]]", "{\"test\": \"1\"}", "", "", commonConfig()); diff.similar(); assertThat(listener.getJsonPatch()).isEqualTo("[[[1,2],[2,3],[1,1]],{\"test\":\"1\"}]"); }
@Test void shouldSeeAddedNode() { Diff diff = Diff.create("{}", "{\"test\": \"1\"}", "", "", commonConfig()); diff.similar(); assertThat(listener.getJsonPatch()).isEqualTo("{\"test\":[\"1\"]}"); }
@Test void shouldSeeEmptyForCheckAnyNode() { Diff diff = Diff.create("{\"test\": \"${json-unit.ignore}\"}", "{\"test\":\"1\"}", "", "", commonConfig()); diff.similar(); assertThat(listener.getJsonPatch()).isEqualTo("{}"); }
@Test void shouldSeeEmptyForCheckAnyBooleanNode() { Diff diff = Diff.create("{\"test\": \"${json-unit.any-boolean}\"}", "{\"test\": true}", "", "", commonConfig()); diff.similar(); assertThat(listener.getJsonPatch()).isEqualTo("{}"); }
@Test void shouldSeeEmptyForCheckAnyNumberNode() { Diff diff = Diff.create("{\"test\": \"${json-unit.any-number}\"}", "{\"test\": 11}", "", "", commonConfig()); diff.similar(); assertThat(listener.getJsonPatch()).isEqualTo("{}"); }
@Test void shouldSeeEmptyForCheckAnyStringNode() { Diff diff = Diff.create("{\"test\": \"${json-unit.any-string}\"}", "{\"test\": \"1\"}", "", "", commonConfig()); diff.similar(); assertThat(listener.getJsonPatch()).isEqualTo("{}"); }
@Test void shouldSeeChangedStringNode() { Diff diff = Diff.create("{\"test\": \"1\"}", "{\"test\": \"2\"}", "", "", commonConfig()); diff.similar(); assertThat(listener.getJsonPatch()).isEqualTo("{\"test\":[\"1\",\"2\"]}"); }
@Test void shouldSeeChangedNumberNode() { Diff diff = Diff.create("{\"test\": 1}", "{\"test\": 2 }", "", "", commonConfig()); diff.similar(); assertThat(listener.getJsonPatch()).isEqualTo("{\"test\":[1,2]}"); }
@Test void shouldSeeChangedBooleanNode() { Diff diff = Diff.create("{\"test\": true}", "{\"test\": false}", "", "", commonConfig()); diff.similar(); assertThat(listener.getJsonPatch()).isEqualTo("{\"test\":[true,false]}"); }
|
JsonPatchListener implements DifferenceListener { public DifferenceContext getContext() { return context; } @Override void diff(final Difference difference, final DifferenceContext differenceContext); List<Difference> getDifferences(); DifferenceContext getContext(); DiffModel getDiffModel(); @SuppressWarnings({"all", "unchecked"}) String getJsonPatch(); }
|
@Test void shouldSeeActualSource() throws JsonProcessingException { Diff diff = Diff.create("{\"test\": \"1\"}", "{}", "", "", commonConfig()); diff.similar(); assertThat(new ObjectMapper().writeValueAsString(listener.getContext().getActualSource())).isEqualTo("{}"); }
@Test void shouldSeeExpectedSource() throws JsonProcessingException { Diff diff = Diff.create("{\"test\": \"1\"}", "{}", "", "", commonConfig()); diff.similar(); assertThat(new ObjectMapper().writeValueAsString(listener.getContext().getExpectedSource())).isEqualTo("{\"test\":\"1\"}"); }
|
AllureCucumber4Jvm implements ConcurrentEventListener { private String getHistoryId(final TestCase testCase) { final String testCaseLocation = testCase.getUri() + ":" + testCase.getLine(); return md5(testCaseLocation); } @SuppressWarnings("unused") AllureCucumber4Jvm(); AllureCucumber4Jvm(final AllureLifecycle lifecycle); @Override void setEventPublisher(final EventPublisher publisher); }
|
@AllureFeatures.History @Test void shouldPersistHistoryIdForScenarios() { final AllureResultsWriterStub writer = new AllureResultsWriterStub(); runFeature(writer, "features/simple.feature"); final List<TestResult> testResults = writer.getTestResults(); assertThat(testResults.get(0).getHistoryId()) .isEqualTo("2f9965e6cc23d5c5f9c5268a2ff6f921"); }
|
AllureCucumber6Jvm implements ConcurrentEventListener { private String getHistoryId(final TestCase testCase) { final String testCaseLocation = testCase.getUri().toString() .substring(testCase.getUri().toString().lastIndexOf('/') + 1) + ":" + testCase.getLine(); return md5(testCaseLocation); } @SuppressWarnings("unused") AllureCucumber6Jvm(); AllureCucumber6Jvm(final AllureLifecycle lifecycle); @Override void setEventPublisher(final EventPublisher publisher); }
|
@AllureFeatures.History @Test void shouldPersistHistoryIdForScenarios() { final AllureResultsWriterStub writer = new AllureResultsWriterStub(); runFeature(writer, "features/simple.feature"); final List<TestResult> testResults = writer.getTestResults(); assertThat(testResults.get(0).getHistoryId()) .isEqualTo("8eea9ed4458a49d418859d1398580671"); }
|
FreemarkerAttachmentRenderer implements AttachmentRenderer<AttachmentData> { @Override public DefaultAttachmentContent render(final AttachmentData data) { try (Writer writer = new StringWriter()) { final Template template = configuration.getTemplate(templateName); template.process(Collections.singletonMap("data", data), writer); return new DefaultAttachmentContent(writer.toString(), "text/html", ".html"); } catch (Exception e) { throw new AttachmentRenderException("Could't render http attachment file", e); } } FreemarkerAttachmentRenderer(final String templateName); @Override DefaultAttachmentContent render(final AttachmentData data); }
|
@AllureFeatures.Attachments @Test void shouldRenderRequestAttachment() { final HttpRequestAttachment data = randomHttpRequestAttachment(); final DefaultAttachmentContent content = new FreemarkerAttachmentRenderer("http-request.ftl") .render(data); assertThat(content) .hasFieldOrPropertyWithValue("contentType", "text/html") .hasFieldOrPropertyWithValue("fileExtension", ".html") .hasFieldOrProperty("content"); }
@AllureFeatures.Attachments @Test void shouldRenderResponseAttachment() { final HttpRequestAttachment data = randomHttpRequestAttachment(); final DefaultAttachmentContent content = new FreemarkerAttachmentRenderer("http-response.ftl") .render(data); assertThat(content) .hasFieldOrPropertyWithValue("contentType", "text/html") .hasFieldOrPropertyWithValue("fileExtension", ".html") .hasFieldOrProperty("content"); }
|
DefaultAttachmentProcessor implements AttachmentProcessor<AttachmentData> { @Override public void addAttachment(final AttachmentData attachmentData, final AttachmentRenderer<AttachmentData> renderer) { final AttachmentContent content = renderer.render(attachmentData); lifecycle.addAttachment( attachmentData.getName(), content.getContentType(), content.getFileExtension(), content.getContent().getBytes(StandardCharsets.UTF_8) ); } DefaultAttachmentProcessor(); DefaultAttachmentProcessor(final AllureLifecycle lifecycle); @Override void addAttachment(final AttachmentData attachmentData,
final AttachmentRenderer<AttachmentData> renderer); }
|
@SuppressWarnings("unchecked") @AllureFeatures.Attachments @Test void shouldProcessAttachments() { final HttpRequestAttachment attachment = randomHttpRequestAttachment(); final AllureLifecycle lifecycle = mock(AllureLifecycle.class); final AttachmentRenderer<AttachmentData> renderer = mock(AttachmentRenderer.class); final AttachmentContent content = randomAttachmentContent(); doReturn(content) .when(renderer) .render(attachment); new DefaultAttachmentProcessor(lifecycle) .addAttachment(attachment, renderer); verify(renderer, times(1)).render(attachment); verify(lifecycle, times(1)) .addAttachment( eq(attachment.getName()), eq(content.getContentType()), eq(content.getFileExtension()), eq(content.getContent().getBytes(StandardCharsets.UTF_8)) ); }
|
AnnotationUtils { public static Set<Label> getLabels(final AnnotatedElement annotatedElement) { return getLabels(annotatedElement.getDeclaredAnnotations()); } private AnnotationUtils(); static Set<Link> getLinks(final AnnotatedElement annotatedElement); static Set<Link> getLinks(final Annotation... annotations); static Set<Link> getLinks(final Collection<Annotation> annotations); static Set<Label> getLabels(final AnnotatedElement annotatedElement); static Set<Label> getLabels(final Annotation... annotations); static Set<Label> getLabels(final Collection<Annotation> annotations); }
|
@Test void shouldExtractDefaultLabels() { final Set<Label> labels = getLabels(WithBddAnnotations.class); assertThat(labels) .extracting(Label::getName, Label::getValue) .contains( tuple(EPIC_LABEL_NAME, "e1"), tuple(FEATURE_LABEL_NAME, "f1"), tuple(STORY_LABEL_NAME, "s1") ); }
@Test void shouldExtractRepeatableLabels() { final Set<Label> labels = getLabels(RepeatableAnnotations.class); assertThat(labels) .extracting(Label::getName, Label::getValue) .contains( tuple(EPIC_LABEL_NAME, "e1"), tuple(EPIC_LABEL_NAME, "e2") ); }
@Test void shouldExtractDirectRepeatableLabels() { final Set<Label> labels = getLabels(DirectRepeatableAnnotations.class); assertThat(labels) .extracting(Label::getName, Label::getValue) .contains( tuple(EPIC_LABEL_NAME, "e1"), tuple(EPIC_LABEL_NAME, "e2") ); }
@Test void shouldExtractCustomAnnotations() { final Set<Label> labels = getLabels(CustomAnnotation.class); assertThat(labels) .extracting(Label::getName, Label::getValue) .contains( tuple("custom", "Some") ); }
@Test void shouldSupportMultiValueAnnotations() { final Set<Label> labels = getLabels(CustomMultiValueAnnotation.class); assertThat(labels) .extracting(Label::getName, Label::getValue) .contains( tuple("custom", "First"), tuple("custom", "Second") ); }
@Test void shouldSupportCustomFixedAnnotations() { final Set<Label> labels = getLabels(CustomFixedAnnotation.class); assertThat(labels) .extracting(Label::getName, Label::getValue) .contains( tuple("custom", "fixed") ); }
@Test void shouldSupportCustomMultiLabelAnnotations() { final Set<Label> labels = getLabels(CustomMultiLabelAnnotation.class); assertThat(labels) .extracting(Label::getName, Label::getValue) .contains( tuple("a", "a1"), tuple("a", "a2"), tuple("b", "b1"), tuple("b", "b2") ); }
@Test void shouldSupportMultiFeature() { final Set<Label> labels = getLabels(WithMultiFeature.class); assertThat(labels) .extracting(Label::getName, Label::getValue) .contains( tuple("feature", "First"), tuple("feature", "Second"), tuple("story", "Other") ); }
@Test void shouldExtractLabelsFromRecursiveAnnotations() { final Set<Label> labels = getLabels(WithRecurse.class); assertThat(labels) .extracting(Label::getName, Label::getValue) .contains( tuple("recursive", "first"), tuple("recursive", "second") ); }
@Test void complexCase() { final Set<Label> labels1 = getLabels(Test1.class); assertThat(labels1) .extracting(Label::getName, Label::getValue) .containsExactlyInAnyOrder( tuple("feature", "A"), tuple("story", "s1"), tuple("owner", "tester1") ); final Set<Label> labels2 = getLabels(Test2.class); assertThat(labels2) .extracting(Label::getName, Label::getValue) .containsExactlyInAnyOrder( tuple("feature", "B"), tuple("story", "s2"), tuple("owner", "tester2") ); final Set<Label> labels3 = getLabels(Test3.class); assertThat(labels3) .extracting(Label::getName, Label::getValue) .containsExactlyInAnyOrder( tuple("feature", "A"), tuple("story", "s1"), tuple("owner", "tester1"), tuple("feature", "B"), tuple("story", "s2"), tuple("owner", "tester2") ); }
|
AnnotationUtils { public static Set<Link> getLinks(final AnnotatedElement annotatedElement) { return getLinks(annotatedElement.getDeclaredAnnotations()); } private AnnotationUtils(); static Set<Link> getLinks(final AnnotatedElement annotatedElement); static Set<Link> getLinks(final Annotation... annotations); static Set<Link> getLinks(final Collection<Annotation> annotations); static Set<Label> getLabels(final AnnotatedElement annotatedElement); static Set<Label> getLabels(final Annotation... annotations); static Set<Label> getLabels(final Collection<Annotation> annotations); }
|
@ResourceLock(value = SYSTEM_PROPERTIES, mode = READ_WRITE) @SystemProperty(name = "allure.link.issue.pattern", value = "https: @SystemProperty(name = "allure.link.tms.pattern", value = "https: @SystemProperty(name = "allure.link.custom.pattern", value = "https: @Test void shouldExtractLinks() { assertThat(getLinks(WithLinks.class)) .extracting( io.qameta.allure.model.Link::getName, io.qameta.allure.model.Link::getType, io.qameta.allure.model.Link::getUrl) .contains( tuple("LINK-1", "custom", "https: tuple("LINK-2", "custom", "https: tuple("", "custom", "https: tuple("ISSUE-1", "issue", "https: tuple("ISSUE-2", "issue", "https: tuple("ISSUE-3", "issue", "https: tuple("TMS-1", "tms", "https: tuple("TMS-2", "tms", "https: tuple("TMS-3", "tms", "https: ); }
@ResourceLock(value = SYSTEM_PROPERTIES, mode = READ_WRITE) @SystemProperty(name = "allure.link.custom.pattern", value = "https: @SystemProperty(name = "allure.link.issue.pattern", value = "https: @Test void shouldExtractCustomLinks() { assertThat(getLinks(WithCustomLink.class)) .extracting(io.qameta.allure.model.Link::getUrl) .containsOnly( "https: "https: "https: ); }
|
Allure { public static void step(final String name) { step(name, Status.PASSED); } private Allure(); static AllureLifecycle getLifecycle(); static void setLifecycle(final AllureLifecycle lifecycle); static void step(final String name); static void step(final String name, final Status status); static void step(final String name, final ThrowableRunnableVoid runnable); static T step(final String name, final ThrowableRunnable<T> runnable); static void step(final ThrowableContextRunnableVoid<StepContext> runnable); static void step(final String name, final ThrowableContextRunnableVoid<StepContext> runnable); static T step(final String name, final ThrowableContextRunnable<T, StepContext> runnable); static T step(final ThrowableContextRunnable<T, StepContext> runnable); static void epic(final String value); static void feature(final String value); static void story(final String value); static void suite(final String value); static void label(final String name, final String value); static T parameter(final String name, final T value); static void issue(final String name, final String url); static void tms(final String name, final String url); static void link(final String url); static void link(final String name, final String url); static void link(final String name, final String type, final String url); static void description(final String description); static void descriptionHtml(final String descriptionHtml); static void attachment(final String name, final String content); static void attachment(final String name, final InputStream content); @Deprecated static void addLabels(final Label... labels); @Deprecated static void addLinks(final Link... links); @Deprecated static void addDescription(final String description); @Deprecated static void addDescriptionHtml(final String descriptionHtml); static void addAttachment(final String name, final String content); static void addAttachment(final String name, final String type, final String content); @SuppressWarnings("PMD.UseObjectForClearerAPI") static void addAttachment(final String name, final String type,
final String content, final String fileExtension); static void addAttachment(final String name, final InputStream content); @SuppressWarnings("PMD.UseObjectForClearerAPI") static void addAttachment(final String name, final String type,
final InputStream content, final String fileExtension); static CompletableFuture<byte[]> addByteAttachmentAsync(
final String name, final String type, final Supplier<byte[]> body); static CompletableFuture<byte[]> addByteAttachmentAsync(
final String name, final String type, final String fileExtension, final Supplier<byte[]> body); static CompletableFuture<InputStream> addStreamAttachmentAsync(
final String name, final String type, final Supplier<InputStream> body); static CompletableFuture<InputStream> addStreamAttachmentAsync(
final String name, final String type, final String fileExtension, final Supplier<InputStream> body); }
|
@Test void shouldAddSteps() { final AllureResults results = runWithinTestContext( () -> { step("first", Status.PASSED); step("second", Status.PASSED); step("third", Status.FAILED); }, Allure::setLifecycle ); assertThat(results.getTestResults()) .flatExtracting(TestResult::getSteps) .extracting(StepResult::getName, StepResult::getStatus) .containsExactly( tuple("first", Status.PASSED), tuple("second", Status.PASSED), tuple("third", Status.FAILED) ); }
@Test void shouldCreateStepsFromLambdas() { final AllureResults results = runWithinTestContext( () -> { step("first", () -> { }); step("second", this::doSomething); step("third", () -> fail("this step is failed")); }, Allure::setLifecycle ); assertThat(results.getTestResults()) .flatExtracting(TestResult::getSteps) .extracting(StepResult::getName, StepResult::getStatus) .containsExactly( tuple("first", Status.PASSED), tuple("second", Status.PASSED), tuple("third", Status.FAILED) ); }
@Test void shouldHideCheckedExceptions() { final AllureResults results = runWithinTestContext( () -> { step("first", Status.PASSED); step("second", () -> { throw new Exception("something wrong"); }); step("third", Status.FAILED); }, Allure::setLifecycle ); assertThat(results.getTestResults()) .extracting(TestResult::getStatus) .containsExactly(Status.BROKEN); assertThat(results.getTestResults()) .extracting(TestResult::getStatusDetails) .extracting(StatusDetails::getMessage) .containsExactly("something wrong"); assertThat(results.getTestResults()) .flatExtracting(TestResult::getSteps) .extracting(StepResult::getName, StepResult::getStatus) .containsExactly( tuple("first", Status.PASSED), tuple("second", Status.BROKEN) ); assertThat(results.getTestResults()) .flatExtracting(TestResult::getSteps) .filteredOn("name", "second") .extracting(StepResult::getStatusDetails) .extracting(StatusDetails::getMessage) .containsExactly("something wrong"); }
|
Allure { public static AllureLifecycle getLifecycle() { if (Objects.isNull(lifecycle)) { lifecycle = new AllureLifecycle(); } return lifecycle; } private Allure(); static AllureLifecycle getLifecycle(); static void setLifecycle(final AllureLifecycle lifecycle); static void step(final String name); static void step(final String name, final Status status); static void step(final String name, final ThrowableRunnableVoid runnable); static T step(final String name, final ThrowableRunnable<T> runnable); static void step(final ThrowableContextRunnableVoid<StepContext> runnable); static void step(final String name, final ThrowableContextRunnableVoid<StepContext> runnable); static T step(final String name, final ThrowableContextRunnable<T, StepContext> runnable); static T step(final ThrowableContextRunnable<T, StepContext> runnable); static void epic(final String value); static void feature(final String value); static void story(final String value); static void suite(final String value); static void label(final String name, final String value); static T parameter(final String name, final T value); static void issue(final String name, final String url); static void tms(final String name, final String url); static void link(final String url); static void link(final String name, final String url); static void link(final String name, final String type, final String url); static void description(final String description); static void descriptionHtml(final String descriptionHtml); static void attachment(final String name, final String content); static void attachment(final String name, final InputStream content); @Deprecated static void addLabels(final Label... labels); @Deprecated static void addLinks(final Link... links); @Deprecated static void addDescription(final String description); @Deprecated static void addDescriptionHtml(final String descriptionHtml); static void addAttachment(final String name, final String content); static void addAttachment(final String name, final String type, final String content); @SuppressWarnings("PMD.UseObjectForClearerAPI") static void addAttachment(final String name, final String type,
final String content, final String fileExtension); static void addAttachment(final String name, final InputStream content); @SuppressWarnings("PMD.UseObjectForClearerAPI") static void addAttachment(final String name, final String type,
final InputStream content, final String fileExtension); static CompletableFuture<byte[]> addByteAttachmentAsync(
final String name, final String type, final Supplier<byte[]> body); static CompletableFuture<byte[]> addByteAttachmentAsync(
final String name, final String type, final String fileExtension, final Supplier<byte[]> body); static CompletableFuture<InputStream> addStreamAttachmentAsync(
final String name, final String type, final Supplier<InputStream> body); static CompletableFuture<InputStream> addStreamAttachmentAsync(
final String name, final String type, final String fileExtension, final Supplier<InputStream> body); }
|
@Test void shouldAddLabels() { final Label first = current().nextObject(Label.class); final Label second = current().nextObject(Label.class); final Label third = current().nextObject(Label.class); final AllureResults results = runWithinTestContext( () -> getLifecycle().updateTestCase(testResult -> testResult.getLabels().addAll(asList(first, second, third))), Allure::setLifecycle ); assertThat(results.getTestResults()) .flatExtracting(TestResult::getLabels) .contains(third, first, second); }
|
Allure { public static <T> T parameter(final String name, final T value) { final Parameter parameter = createParameter(name, value); getLifecycle().updateTestCase(testResult -> testResult.getParameters().add(parameter)); return value; } private Allure(); static AllureLifecycle getLifecycle(); static void setLifecycle(final AllureLifecycle lifecycle); static void step(final String name); static void step(final String name, final Status status); static void step(final String name, final ThrowableRunnableVoid runnable); static T step(final String name, final ThrowableRunnable<T> runnable); static void step(final ThrowableContextRunnableVoid<StepContext> runnable); static void step(final String name, final ThrowableContextRunnableVoid<StepContext> runnable); static T step(final String name, final ThrowableContextRunnable<T, StepContext> runnable); static T step(final ThrowableContextRunnable<T, StepContext> runnable); static void epic(final String value); static void feature(final String value); static void story(final String value); static void suite(final String value); static void label(final String name, final String value); static T parameter(final String name, final T value); static void issue(final String name, final String url); static void tms(final String name, final String url); static void link(final String url); static void link(final String name, final String url); static void link(final String name, final String type, final String url); static void description(final String description); static void descriptionHtml(final String descriptionHtml); static void attachment(final String name, final String content); static void attachment(final String name, final InputStream content); @Deprecated static void addLabels(final Label... labels); @Deprecated static void addLinks(final Link... links); @Deprecated static void addDescription(final String description); @Deprecated static void addDescriptionHtml(final String descriptionHtml); static void addAttachment(final String name, final String content); static void addAttachment(final String name, final String type, final String content); @SuppressWarnings("PMD.UseObjectForClearerAPI") static void addAttachment(final String name, final String type,
final String content, final String fileExtension); static void addAttachment(final String name, final InputStream content); @SuppressWarnings("PMD.UseObjectForClearerAPI") static void addAttachment(final String name, final String type,
final InputStream content, final String fileExtension); static CompletableFuture<byte[]> addByteAttachmentAsync(
final String name, final String type, final Supplier<byte[]> body); static CompletableFuture<byte[]> addByteAttachmentAsync(
final String name, final String type, final String fileExtension, final Supplier<byte[]> body); static CompletableFuture<InputStream> addStreamAttachmentAsync(
final String name, final String type, final Supplier<InputStream> body); static CompletableFuture<InputStream> addStreamAttachmentAsync(
final String name, final String type, final String fileExtension, final Supplier<InputStream> body); }
|
@Test void shouldAddParameter() { final Parameter first = current().nextObject(Parameter.class); final Parameter second = current().nextObject(Parameter.class); final Parameter third = current().nextObject(Parameter.class); final AllureResults results = runWithinTestContext( () -> { parameter(first.getName(), first.getValue()); parameter(second.getName(), second.getValue()); parameter(third.getName(), third.getValue()); }, Allure::setLifecycle ); assertThat(results.getTestResults()) .flatExtracting(TestResult::getParameters) .extracting(Parameter::getName, Parameter::getValue) .contains( tuple(first.getName(), first.getValue()), tuple(second.getName(), second.getValue()), tuple(third.getName(), third.getValue()) ); }
|
Allure { public static void link(final String url) { link(null, url); } private Allure(); static AllureLifecycle getLifecycle(); static void setLifecycle(final AllureLifecycle lifecycle); static void step(final String name); static void step(final String name, final Status status); static void step(final String name, final ThrowableRunnableVoid runnable); static T step(final String name, final ThrowableRunnable<T> runnable); static void step(final ThrowableContextRunnableVoid<StepContext> runnable); static void step(final String name, final ThrowableContextRunnableVoid<StepContext> runnable); static T step(final String name, final ThrowableContextRunnable<T, StepContext> runnable); static T step(final ThrowableContextRunnable<T, StepContext> runnable); static void epic(final String value); static void feature(final String value); static void story(final String value); static void suite(final String value); static void label(final String name, final String value); static T parameter(final String name, final T value); static void issue(final String name, final String url); static void tms(final String name, final String url); static void link(final String url); static void link(final String name, final String url); static void link(final String name, final String type, final String url); static void description(final String description); static void descriptionHtml(final String descriptionHtml); static void attachment(final String name, final String content); static void attachment(final String name, final InputStream content); @Deprecated static void addLabels(final Label... labels); @Deprecated static void addLinks(final Link... links); @Deprecated static void addDescription(final String description); @Deprecated static void addDescriptionHtml(final String descriptionHtml); static void addAttachment(final String name, final String content); static void addAttachment(final String name, final String type, final String content); @SuppressWarnings("PMD.UseObjectForClearerAPI") static void addAttachment(final String name, final String type,
final String content, final String fileExtension); static void addAttachment(final String name, final InputStream content); @SuppressWarnings("PMD.UseObjectForClearerAPI") static void addAttachment(final String name, final String type,
final InputStream content, final String fileExtension); static CompletableFuture<byte[]> addByteAttachmentAsync(
final String name, final String type, final Supplier<byte[]> body); static CompletableFuture<byte[]> addByteAttachmentAsync(
final String name, final String type, final String fileExtension, final Supplier<byte[]> body); static CompletableFuture<InputStream> addStreamAttachmentAsync(
final String name, final String type, final Supplier<InputStream> body); static CompletableFuture<InputStream> addStreamAttachmentAsync(
final String name, final String type, final String fileExtension, final Supplier<InputStream> body); }
|
@Test void shouldAddLinks() { final io.qameta.allure.model.Link first = current().nextObject(Link.class); final io.qameta.allure.model.Link second = current().nextObject(Link.class); final io.qameta.allure.model.Link third = current().nextObject(Link.class); final AllureResults results = runWithinTestContext( () -> { link(first.getName(), first.getType(), first.getUrl()); link(second.getName(), second.getUrl()); link(third.getUrl()); }, Allure::setLifecycle ); assertThat(results.getTestResults()) .flatExtracting(TestResult::getLinks) .extracting(Link::getName, Link::getType, Link::getUrl) .contains( tuple(first.getName(), first.getType(), first.getUrl()), tuple(second.getName(), null, second.getUrl()), tuple(null, null, third.getUrl()) ); }
|
Allure { public static void description(final String description) { getLifecycle().updateTestCase(executable -> executable.setDescription(description)); } private Allure(); static AllureLifecycle getLifecycle(); static void setLifecycle(final AllureLifecycle lifecycle); static void step(final String name); static void step(final String name, final Status status); static void step(final String name, final ThrowableRunnableVoid runnable); static T step(final String name, final ThrowableRunnable<T> runnable); static void step(final ThrowableContextRunnableVoid<StepContext> runnable); static void step(final String name, final ThrowableContextRunnableVoid<StepContext> runnable); static T step(final String name, final ThrowableContextRunnable<T, StepContext> runnable); static T step(final ThrowableContextRunnable<T, StepContext> runnable); static void epic(final String value); static void feature(final String value); static void story(final String value); static void suite(final String value); static void label(final String name, final String value); static T parameter(final String name, final T value); static void issue(final String name, final String url); static void tms(final String name, final String url); static void link(final String url); static void link(final String name, final String url); static void link(final String name, final String type, final String url); static void description(final String description); static void descriptionHtml(final String descriptionHtml); static void attachment(final String name, final String content); static void attachment(final String name, final InputStream content); @Deprecated static void addLabels(final Label... labels); @Deprecated static void addLinks(final Link... links); @Deprecated static void addDescription(final String description); @Deprecated static void addDescriptionHtml(final String descriptionHtml); static void addAttachment(final String name, final String content); static void addAttachment(final String name, final String type, final String content); @SuppressWarnings("PMD.UseObjectForClearerAPI") static void addAttachment(final String name, final String type,
final String content, final String fileExtension); static void addAttachment(final String name, final InputStream content); @SuppressWarnings("PMD.UseObjectForClearerAPI") static void addAttachment(final String name, final String type,
final InputStream content, final String fileExtension); static CompletableFuture<byte[]> addByteAttachmentAsync(
final String name, final String type, final Supplier<byte[]> body); static CompletableFuture<byte[]> addByteAttachmentAsync(
final String name, final String type, final String fileExtension, final Supplier<byte[]> body); static CompletableFuture<InputStream> addStreamAttachmentAsync(
final String name, final String type, final Supplier<InputStream> body); static CompletableFuture<InputStream> addStreamAttachmentAsync(
final String name, final String type, final String fileExtension, final Supplier<InputStream> body); }
|
@Test void shouldAddDescription() { final String description = randomName(); final AllureResults results = runWithinTestContext( () -> description(description), Allure::setLifecycle ); assertThat(results.getTestResults()) .extracting(TestResult::getDescription) .containsExactly(description); }
|
Allure { public static void descriptionHtml(final String descriptionHtml) { getLifecycle().updateTestCase(executable -> executable.setDescriptionHtml(descriptionHtml)); } private Allure(); static AllureLifecycle getLifecycle(); static void setLifecycle(final AllureLifecycle lifecycle); static void step(final String name); static void step(final String name, final Status status); static void step(final String name, final ThrowableRunnableVoid runnable); static T step(final String name, final ThrowableRunnable<T> runnable); static void step(final ThrowableContextRunnableVoid<StepContext> runnable); static void step(final String name, final ThrowableContextRunnableVoid<StepContext> runnable); static T step(final String name, final ThrowableContextRunnable<T, StepContext> runnable); static T step(final ThrowableContextRunnable<T, StepContext> runnable); static void epic(final String value); static void feature(final String value); static void story(final String value); static void suite(final String value); static void label(final String name, final String value); static T parameter(final String name, final T value); static void issue(final String name, final String url); static void tms(final String name, final String url); static void link(final String url); static void link(final String name, final String url); static void link(final String name, final String type, final String url); static void description(final String description); static void descriptionHtml(final String descriptionHtml); static void attachment(final String name, final String content); static void attachment(final String name, final InputStream content); @Deprecated static void addLabels(final Label... labels); @Deprecated static void addLinks(final Link... links); @Deprecated static void addDescription(final String description); @Deprecated static void addDescriptionHtml(final String descriptionHtml); static void addAttachment(final String name, final String content); static void addAttachment(final String name, final String type, final String content); @SuppressWarnings("PMD.UseObjectForClearerAPI") static void addAttachment(final String name, final String type,
final String content, final String fileExtension); static void addAttachment(final String name, final InputStream content); @SuppressWarnings("PMD.UseObjectForClearerAPI") static void addAttachment(final String name, final String type,
final InputStream content, final String fileExtension); static CompletableFuture<byte[]> addByteAttachmentAsync(
final String name, final String type, final Supplier<byte[]> body); static CompletableFuture<byte[]> addByteAttachmentAsync(
final String name, final String type, final String fileExtension, final Supplier<byte[]> body); static CompletableFuture<InputStream> addStreamAttachmentAsync(
final String name, final String type, final Supplier<InputStream> body); static CompletableFuture<InputStream> addStreamAttachmentAsync(
final String name, final String type, final String fileExtension, final Supplier<InputStream> body); }
|
@Test void shouldAddDescriptionHtml() { final String descriptionHtml = randomName(); final AllureResults results = runWithinTestContext( () -> descriptionHtml(descriptionHtml), Allure::setLifecycle ); assertThat(results.getTestResults()) .extracting(TestResult::getDescriptionHtml) .containsExactly(descriptionHtml); }
|
FileSystemResultsWriter implements AllureResultsWriter { @Override public void write(final TestResult testResult) { final String testResultName = Objects.isNull(testResult.getUuid()) ? generateTestResultName() : generateTestResultName(testResult.getUuid()); createDirectories(outputDirectory); final Path file = outputDirectory.resolve(testResultName); try { mapper.writeValue(file.toFile(), testResult); } catch (IOException e) { throw new AllureResultsWriteException("Could not write Allure test result", e); } } FileSystemResultsWriter(final Path outputDirectory); @Override void write(final TestResult testResult); @Override void write(final TestResultContainer testResultContainer); @Override void write(final String source, final InputStream attachment); }
|
@Test void shouldNotFailIfNoResultsDirectory(@TempDir final Path folder) { Path resolve = folder.resolve("some-directory"); FileSystemResultsWriter writer = new FileSystemResultsWriter(resolve); final TestResult testResult = current().nextObject(TestResult.class, "steps"); writer.write(testResult); }
|
AllureCucumber5Jvm implements ConcurrentEventListener { private String getHistoryId(final TestCase testCase) { final String testCaseLocation = testCase.getUri().toString() .substring(testCase.getUri().toString().lastIndexOf('/') + 1) + ":" + testCase.getLine(); return md5(testCaseLocation); } @SuppressWarnings("unused") AllureCucumber5Jvm(); AllureCucumber5Jvm(final AllureLifecycle lifecycle); @Override void setEventPublisher(final EventPublisher publisher); }
|
@AllureFeatures.History @Test void shouldPersistHistoryIdForScenarios() { final AllureResultsWriterStub writer = new AllureResultsWriterStub(); runFeature(writer, "features/simple.feature"); final List<TestResult> testResults = writer.getTestResults(); assertThat(testResults.get(0).getHistoryId()) .isEqualTo("8eea9ed4458a49d418859d1398580671"); }
|
Utils { public static void p(Object... args) { if (!BuildConfig.DEBUG) return; p(TextUtils.join(", ", args)); } static void p(Object... args); static void p(String msg); static void p(String format, Object... args); static int runOneCmdByRoot(String cmd, boolean isWait); static int screenshot(); static boolean hasRoot(); static int runCmd(String cmd, boolean isRoot, boolean isWait); static String is2String(InputStream is); }
|
@Test public void testP() throws Exception { p("msg"); p("msg", "arg0"); p(1, "arg0"); }
@Test public void testEnv() { p(System.getenv()); }
|
MulticastResult implements Serializable { public List<Result> getResults() { return results; } private MulticastResult(Builder builder); long getMulticastId(); int getSuccess(); int getTotal(); int getFailure(); int getCanonicalIds(); List<Result> getResults(); List<Long> getRetryMulticastIds(); @Override String toString(); }
|
@Test(expected = UnsupportedOperationException.class) public void testResultsIsImmutable() { MulticastResult result = new MulticastResult.Builder(1, 2, 3, 4).build(); result.getResults().clear(); }
|
Sender { public Result sendNoRetry(Message message, String registrationId) throws IOException { StringBuilder body = newBody(PARAM_REGISTRATION_ID, registrationId); Boolean delayWhileIdle = message.isDelayWhileIdle(); if (delayWhileIdle != null) { addParameter(body, PARAM_DELAY_WHILE_IDLE, delayWhileIdle ? "1" : "0"); } Boolean dryRun = message.isDryRun(); if (dryRun != null) { addParameter(body, PARAM_DRY_RUN, dryRun ? "1" : "0"); } String collapseKey = message.getCollapseKey(); if (collapseKey != null) { addParameter(body, PARAM_COLLAPSE_KEY, collapseKey); } String restrictedPackageName = message.getRestrictedPackageName(); if (restrictedPackageName != null) { addParameter(body, PARAM_RESTRICTED_PACKAGE_NAME, restrictedPackageName); } Integer timeToLive = message.getTimeToLive(); if (timeToLive != null) { addParameter(body, PARAM_TIME_TO_LIVE, Integer.toString(timeToLive)); } for (Entry<String, String> entry : message.getData().entrySet()) { String key = entry.getKey(); String value = entry.getValue(); if (key == null || value == null) { logger.warning("Ignoring payload entry thas has null: " + entry); } else { key = PARAM_PAYLOAD_PREFIX + key; addParameter(body, key, URLEncoder.encode(value, UTF8)); } } String requestBody = body.toString(); logger.finest("Request body: " + requestBody); HttpURLConnection conn; int status; try { conn = post(GCM_SEND_ENDPOINT, requestBody); status = conn.getResponseCode(); } catch (IOException e) { logger.log(Level.FINE, "IOException posting to GCM", e); return null; } if (status / 100 == 5) { logger.fine("GCM service is unavailable (status " + status + ")"); return null; } String responseBody; if (status != 200) { try { responseBody = getAndClose(conn.getErrorStream()); logger.finest("Plain post error response: " + responseBody); } catch (IOException e) { responseBody = "N/A"; logger.log(Level.FINE, "Exception reading response: ", e); } throw new InvalidRequestException(status, responseBody); } else { try { responseBody = getAndClose(conn.getInputStream()); } catch (IOException e) { logger.log(Level.WARNING, "Exception reading response: ", e); return null; } } String[] lines = responseBody.split("\n"); if (lines.length == 0 || lines[0].equals("")) { throw new IOException("Received empty response from GCM service."); } String firstLine = lines[0]; String[] responseParts = split(firstLine); String token = responseParts[0]; String value = responseParts[1]; if (token.equals(TOKEN_MESSAGE_ID)) { Builder builder = new Result.Builder().messageId(value); if (lines.length > 1) { String secondLine = lines[1]; responseParts = split(secondLine); token = responseParts[0]; value = responseParts[1]; if (token.equals(TOKEN_CANONICAL_REG_ID)) { builder.canonicalRegistrationId(value); } else { logger.warning("Invalid response from GCM: " + responseBody); } } Result result = builder.build(); if (logger.isLoggable(Level.FINE)) { logger.fine("Message created succesfully (" + result + ")"); } return result; } else if (token.equals(TOKEN_ERROR)) { return new Result.Builder().errorCode(value).build(); } else { throw new IOException("Invalid response from GCM: " + responseBody); } } Sender(String key); Result send(Message message, String registrationId, int retries); Result sendNoRetry(Message message, String registrationId); MulticastResult send(Message message, List<String> regIds, int retries); MulticastResult sendNoRetry(Message message,
List<String> registrationIds); }
|
@Test(expected = IOException.class) public void testSendNoRetry_noToken() throws Exception { setResponseExpectations(200, "no token"); sender.sendNoRetry(message, regId); }
@Test(expected = IOException.class) public void testSendNoRetry_invalidToken() throws Exception { setResponseExpectations(200, "bad=token"); sender.sendNoRetry(message, regId); }
@Test(expected = IOException.class) public void testSendNoRetry_emptyToken() throws Exception { setResponseExpectations(200, "token="); sender.sendNoRetry(message, regId); }
@Test public void testSendNoRetry_invalidHttpStatusCode() throws Exception { setResponseExpectations(108, "id=4815162342"); try { sender.sendNoRetry(message, regId); } catch (InvalidRequestException e) { assertEquals(108, e.getHttpStatusCode()); assertEquals("id=4815162342", e.getDescription()); } }
@Test(expected = IllegalArgumentException.class) public void testSendNoRetry_noRegistrationId() throws Exception { sender.sendNoRetry(new Message.Builder().build(), (String) null); }
@Test(expected = IllegalArgumentException.class) public void testSendNoRetry_json_nullRegIds() throws Exception { sender.sendNoRetry(message, (List<String>) null); }
@Test(expected = IllegalArgumentException.class) public void testSendNoRetry_json_emptyRegIds() throws Exception { sender.sendNoRetry(message, Collections.<String>emptyList()); }
@Test public void testSendNoRetry_json_badRequest() throws Exception { setResponseExpectations(42, "bad json"); try { sender.sendNoRetry(message, Arrays.asList("108")); } catch (InvalidRequestException e) { assertEquals(42, e.getHttpStatusCode()); assertEquals("bad json", e.getDescription()); assertRequestJsonBody("108"); } }
@Test public void testSendNoRetry_json_badRequest_nullError() throws Exception { setResponseExpectations(42, null); try { sender.sendNoRetry(message, Arrays.asList("108")); } catch (InvalidRequestException e) { assertEquals(42, e.getHttpStatusCode()); assertEquals("", e.getDescription()); assertRequestJsonBody("108"); } }
@Test() public void testSendNoRetry_json_ok() throws Exception { String json = replaceQuotes("\n" + "{" + " 'multicast_id': 108," + " 'success': 2," + " 'failure': 1," + " 'canonical_ids': 1," + " 'results': [" + " {'message_id': '16'}, " + " {'error': 'DOH!'}, " + " {'message_id': '23', 'registration_id': '42'}" + " ]" + "}"); setResponseExpectations(200, json); MulticastResult multicastResult = sender.sendNoRetry(message, Arrays.asList("4", "8", "15")); assertNotNull(multicastResult); assertEquals(3, multicastResult.getTotal()); assertEquals(2, multicastResult.getSuccess()); assertEquals(1, multicastResult.getFailure()); assertEquals(1, multicastResult.getCanonicalIds()); assertEquals(108, multicastResult.getMulticastId()); List<Result> results = multicastResult.getResults(); assertNotNull(results); assertEquals(3, results.size()); assertResult(results.get(0), "16", null, null); assertResult(results.get(1), null, "DOH!", null); assertResult(results.get(2), "23", null, "42"); assertRequestJsonBody("4", "8", "15"); }
@Test public void testSendNoRetry_ok() throws Exception { setResponseExpectations(200, "id=4815162342"); Result result = sender.sendNoRetry(message, regId); assertNotNull(result); assertEquals("4815162342", result.getMessageId()); assertNull(result.getCanonicalRegistrationId()); assertNull(result.getErrorCodeName()); assertRequestBody(); }
@Test public void testSendNoRetry_ok_canonical() throws Exception { setResponseExpectations(200, "id=4815162342\nregistration_id=108"); Result result = sender.sendNoRetry(message, regId); assertNotNull(result); assertEquals("4815162342", result.getMessageId()); assertEquals("108", result.getCanonicalRegistrationId()); assertNull(result.getErrorCodeName()); assertRequestBody(); }
@Test public void testSendNoRetry_unauthorized() throws Exception { setResponseExpectations(401, ""); try { sender.sendNoRetry(message, regId); fail("Should have thrown InvalidRequestException"); } catch (InvalidRequestException e) { assertEquals(401, e.getHttpStatusCode()); } assertRequestBody(); }
@Test public void testSendNoRetry_unauthorized_nullStream() throws Exception { setResponseExpectations(401, null); try { sender.sendNoRetry(message, regId); fail("Should have thrown InvalidRequestException"); } catch (InvalidRequestException e) { assertEquals(401, e.getHttpStatusCode()); assertEquals("", e.getDescription()); } assertRequestBody(); }
@Test public void testSendNoRetry_error() throws Exception { setResponseExpectations(200, "Error=D'OH!"); Result result = sender.sendNoRetry(message, regId); assertNull(result.getMessageId()); assertNull(result.getCanonicalRegistrationId()); assertEquals("D'OH!", result.getErrorCodeName()); assertRequestBody(); }
@Test public void testSendNoRetry_serviceUnavailable() throws Exception { setResponseExpectations(503, ""); Result result = sender.sendNoRetry(message, regId); assertNull(result); assertRequestBody(); }
@Test public void testSendNoRetry_internalServerError() throws Exception { setResponseExpectations(500, ""); Result result = sender.sendNoRetry(message, regId); assertNull(result); assertRequestBody(); }
@Test(expected = IOException.class) public void testSendNoRetry_emptyBody() throws Exception { setResponseExpectations(200, ""); sender.sendNoRetry(message, regId); }
|
MulticastResult implements Serializable { public List<Long> getRetryMulticastIds() { return retryMulticastIds; } private MulticastResult(Builder builder); long getMulticastId(); int getSuccess(); int getTotal(); int getFailure(); int getCanonicalIds(); List<Result> getResults(); List<Long> getRetryMulticastIds(); @Override String toString(); }
|
@Test(expected = UnsupportedOperationException.class) public void testRetryMulticastIdsIsImmutable() { MulticastResult result = new MulticastResult.Builder(1, 2, 3, 4).build(); result.getRetryMulticastIds().clear(); }
|
Sender { protected static final Map<String, String> newKeyValues(String key, String value) { Map<String, String> keyValues = new HashMap<String, String>(1); keyValues.put(nonNull(key), nonNull(value)); return keyValues; } Sender(String key); Result send(Message message, String registrationId, int retries); Result sendNoRetry(Message message, String registrationId); MulticastResult send(Message message, List<String> regIds, int retries); MulticastResult sendNoRetry(Message message,
List<String> registrationIds); }
|
@Test public void testNewKeyValues() { Map<String, String> x = Sender.newKeyValues("key", "value"); assertEquals(1, x.size()); assertEquals("value", x.get("key")); }
@Test(expected = IllegalArgumentException.class) public void testNewKeyValues_nullKey() { Sender.newKeyValues(null, "value"); }
@Test(expected = IllegalArgumentException.class) public void testNewKeyValues_nullValue() { Sender.newKeyValues("key", null); }
|
Sender { protected static StringBuilder newBody(String name, String value) { return new StringBuilder(nonNull(name)).append('=').append(nonNull(value)); } Sender(String key); Result send(Message message, String registrationId, int retries); Result sendNoRetry(Message message, String registrationId); MulticastResult send(Message message, List<String> regIds, int retries); MulticastResult sendNoRetry(Message message,
List<String> registrationIds); }
|
@Test public void testNewBody() { StringBuilder body = Sender.newBody("name", "value"); assertEquals("name=value", body.toString()); }
@Test(expected = IllegalArgumentException.class) public void testNewBody_nullKey() { Sender.newBody(null, "value"); }
@Test(expected = IllegalArgumentException.class) public void testNewBody_nullValue() { Sender.newBody("key", null); }
|
Sender { protected static void addParameter(StringBuilder body, String name, String value) { nonNull(body).append('&') .append(nonNull(name)).append('=').append(nonNull(value)); } Sender(String key); Result send(Message message, String registrationId, int retries); Result sendNoRetry(Message message, String registrationId); MulticastResult send(Message message, List<String> regIds, int retries); MulticastResult sendNoRetry(Message message,
List<String> registrationIds); }
|
@Test public void testAddParameter() { StringBuilder body = new StringBuilder("P=NP"); Sender.addParameter(body, "name", "value"); assertEquals("P=NP&name=value", body.toString()); }
@Test(expected = IllegalArgumentException.class) public void testAddParameter_nullBody() { Sender.addParameter(null, "key", "value"); }
@Test(expected = IllegalArgumentException.class) public void testAddParameter_nullKey() { StringBuilder body = new StringBuilder(); Sender.addParameter(body, null, "value"); }
@Test(expected = IllegalArgumentException.class) public void testAddParameter_nullValue() { StringBuilder body = new StringBuilder(); Sender.addParameter(body, "key", null); }
|
Sender { protected static String getString(InputStream stream) throws IOException { if (stream == null) { return ""; } BufferedReader reader = new BufferedReader(new InputStreamReader(stream)); StringBuilder content = new StringBuilder(); String newLine; do { newLine = reader.readLine(); if (newLine != null) { content.append(newLine).append('\n'); } } while (newLine != null); if (content.length() > 0) { content.setLength(content.length() - 1); } return content.toString(); } Sender(String key); Result send(Message message, String registrationId, int retries); Result sendNoRetry(Message message, String registrationId); MulticastResult send(Message message, List<String> regIds, int retries); MulticastResult sendNoRetry(Message message,
List<String> registrationIds); }
|
@Test public void testGetString_oneLine() throws Exception { String expected = "108"; InputStream stream = new ByteArrayInputStream(expected.getBytes()); String actual = Sender.getString(stream); assertEquals(expected, actual); }
@Test public void testGetString_stripsLastLine() throws Exception { InputStream stream = new ByteArrayInputStream("108\n".getBytes()); String stripped = Sender.getString(stream); assertEquals("108", stripped); }
@Test public void testGetString_multipleLines() throws Exception { String expected = "4\n8\n15\n\n16\n23\n42"; InputStream stream = new ByteArrayInputStream(expected.getBytes()); String actual = Sender.getString(stream); assertEquals(expected, actual); }
|
Sender { protected HttpURLConnection post(String url, String body) throws IOException { return post(url, "application/x-www-form-urlencoded;charset=UTF-8", body); } Sender(String key); Result send(Message message, String registrationId, int retries); Result sendNoRetry(Message message, String registrationId); MulticastResult send(Message message, List<String> regIds, int retries); MulticastResult sendNoRetry(Message message,
List<String> registrationIds); }
|
@Test(expected = IllegalArgumentException.class) public void testPost_noUrl() throws Exception { sender.post(null, "whatever"); }
@Test(expected = IllegalArgumentException.class) public void testPost_noBody() throws Exception { sender.post(Constants.GCM_SEND_ENDPOINT, null); }
@Test public void testPost() throws Exception { String requestBody = "req"; String responseBody = "resp"; setResponseExpectations(200, responseBody); HttpURLConnection response = sender.post(Constants.GCM_SEND_ENDPOINT, requestBody); assertEquals(requestBody, new String(outputStream.toByteArray())); verify(mockedConn).setRequestMethod("POST"); verify(mockedConn).setFixedLengthStreamingMode(requestBody.length()); verify(mockedConn).setRequestProperty("Content-Type", "application/x-www-form-urlencoded;charset=UTF-8"); verify(mockedConn).setRequestProperty("Authorization", "key=" + authKey); assertEquals(200, response.getResponseCode()); }
@Test public void testPost_customType() throws Exception { String requestBody = "req"; String responseBody = "resp"; setResponseExpectations(200, responseBody); HttpURLConnection response = sender.post(Constants.GCM_SEND_ENDPOINT, "stuff", requestBody); assertEquals(requestBody, new String(outputStream.toByteArray())); verify(mockedConn).setRequestMethod("POST"); verify(mockedConn).setFixedLengthStreamingMode(requestBody.length()); verify(mockedConn).setRequestProperty("Content-Type", "stuff"); verify(mockedConn).setRequestProperty("Authorization", "key=" + authKey); assertEquals(200, response.getResponseCode()); }
|
Message implements Serializable { public Map<String, String> getData() { return data; } private Message(Builder builder); String getCollapseKey(); Boolean isDelayWhileIdle(); Integer getTimeToLive(); Boolean isDryRun(); String getRestrictedPackageName(); Map<String, String> getData(); @Override String toString(); }
|
@Test(expected = UnsupportedOperationException.class) public void testPayloadDataIsImmutable() { Message message = new Message.Builder().build(); message.getData().clear(); }
|
ArtifactSizeEnforcerRule implements EnforcerRule { protected String getPackaging(EnforcerRuleHelper helper) throws EnforcerRuleException { String packaging; try { packaging = (String) helper.evaluate(PROJECT_PACKAGING_PROP); } catch (ExpressionEvaluationException e) { throw new EnforcerRuleException(e.getMessage()); } switch (packaging) { case JAR: return JAR; case BUNDLE: return JAR; default: return packaging; } } @Override void execute(EnforcerRuleHelper helper); @Override boolean isCacheable(); @Override boolean isResultValid(EnforcerRule enforcerRule); @Override String getCacheId(); ArtifactSizeEnforcerRule setMaxArtifactSize(String maxArtifactSize); ArtifactSizeEnforcerRule setArtifactLocation(String artifactLocation); static final String PROJECT_PACKAGING_PROP; static final String PROJECT_ARTIFACT_ID_PROP; static final String PROJECT_VERSION_PROP; static final String PROJECT_BUILD_DIR_PROP; static final String DEFAULT_MAX_ARTIFACT_SIZE; static final String BYTES; static final String MEGA_BYTES; static final String KILO_BYTES; static final String JAR; static final String BUNDLE; static final List<String> SUPPORTED_PACKAGE_TYPES; static final String MAX_FILE_SIZE_EXCEEDED_MSG; static final String DEFAULT_ARTIFACT_INFO_MSG; static final String UNKNOWN_ARTIFACT_SIZE_UNIT_MSG; }
|
@Test public void unknownPackaging() { ArtifactSizeEnforcerRule enforcer = new ArtifactSizeEnforcerRule(); defaultMockhelper.packaging("UnknownPackageType"); try { String packaging = enforcer.getPackaging(defaultMockhelper); assertTrue(!SUPPORTED_PACKAGE_TYPES.contains(packaging)); } catch (EnforcerRuleException e) { fail("ArtifactSizerEnforcerRule was unable to skip an unknown packing type."); } }
|
ArtifactSizeEnforcerRule implements EnforcerRule { @Override public void execute(EnforcerRuleHelper helper) throws EnforcerRuleException { if (skip) { return; } String packaging = getPackaging(helper); if (!SUPPORTED_PACKAGE_TYPES.contains(packaging)) { helper .getLog() .info( String.format( "Unsupported package type %s. Skipping artifact size enforcement.", packaging)); return; } String artifactPath = getArtifactPath(helper); long maxArtifactSizeBytes = maxArtifactSizeToBytes(helper); long artifactSize = getArtifact(artifactPath).length(); if (artifactSize >= maxArtifactSizeBytes) { throw new EnforcerRuleException( String.format( MAX_FILE_SIZE_EXCEEDED_MSG, artifactPath, artifactSize, maxArtifactSizeBytes)); } } @Override void execute(EnforcerRuleHelper helper); @Override boolean isCacheable(); @Override boolean isResultValid(EnforcerRule enforcerRule); @Override String getCacheId(); ArtifactSizeEnforcerRule setMaxArtifactSize(String maxArtifactSize); ArtifactSizeEnforcerRule setArtifactLocation(String artifactLocation); static final String PROJECT_PACKAGING_PROP; static final String PROJECT_ARTIFACT_ID_PROP; static final String PROJECT_VERSION_PROP; static final String PROJECT_BUILD_DIR_PROP; static final String DEFAULT_MAX_ARTIFACT_SIZE; static final String BYTES; static final String MEGA_BYTES; static final String KILO_BYTES; static final String JAR; static final String BUNDLE; static final List<String> SUPPORTED_PACKAGE_TYPES; static final String MAX_FILE_SIZE_EXCEEDED_MSG; static final String DEFAULT_ARTIFACT_INFO_MSG; static final String UNKNOWN_ARTIFACT_SIZE_UNIT_MSG; }
|
@Test public void successfullyDiscoverArtifact() throws IOException { tempFolder.newFile(SAMPLE_ARTIFACT_FILE_NAME); ArtifactSizeEnforcerRule enforcer = new ArtifactSizeEnforcerRule(); try { enforcer.execute(defaultMockhelper); } catch (EnforcerRuleException e) { fail("Failed to discover artifact."); } }
@Test(expected = EnforcerRuleException.class) public void failToDiscoverArtifact() throws EnforcerRuleException { ArtifactSizeEnforcerRule enforcer = new ArtifactSizeEnforcerRule(); enforcer.execute(defaultMockhelper); }
|
InterfaceCodeGenerator { public Map<File, String> analyze(boolean _ignoreDtd) throws Exception { if (_ignoreDtd) { docFac.setValidating(false); docFac.setNamespaceAware(true); docFac.setFeature("http: docFac.setFeature("http: docFac.setFeature("http: docFac.setFeature("http: } DocumentBuilder builder = docFac.newDocumentBuilder(); Document document = builder.parse(new InputSource(new StringReader(introspectionData))); Element root = document.getDocumentElement(); if (!StringUtil.isBlank(nodeName) && !StringUtil.isBlank(root.getAttribute("name"))) { if (!nodeName.equals(root.getAttribute("name"))) { logger.error("Retrieved node '{}' does not match requested node name '{}'!", root.getAttribute("name"), nodeName); return null; } } List<Element> interfaceElements = convertToElementList(root.getChildNodes()); Map<File, String> filesAndContents = new LinkedHashMap<>(); for (Element ife : interfaceElements) { if (!StringUtil.isBlank(busName) && ife.getAttribute("name").startsWith(busName)) { filesAndContents.putAll(extractAll(ife)); continue; } filesAndContents.putAll(extractAll(ife)); } return filesAndContents; } InterfaceCodeGenerator(String _introspectionData, String _objectPath, String _busName); Map<File, String> analyze(boolean _ignoreDtd); static void main(String[] args); }
|
@Test void testCreateFirewallInterfaces() { String objectPath = "/org/fedoraproject/FirewallD1"; String busName = "org.fedoraproject.FirewallD1"; boolean ignoreDtd = true; Logger logger = LoggerFactory.getLogger(InterfaceCodeGenerator.class); if (!StringUtils.isBlank(busName)) { String introspectionData = FileIoUtil.readFileToString("src/test/resources/CreateInterface/firewall/org.fedoraproject.FirewallD1.xml"); InterfaceCodeGenerator ci2 = new InterfaceCodeGenerator(introspectionData, objectPath, busName); try { Map<File, String> analyze = ci2.analyze(ignoreDtd); assertEquals(20, analyze.size()); } catch (Exception _ex) { logger.error("Error while analyzing introspection data", _ex); } } }
@Test void testCreateNetworkManagerWirelessInterface() { String objectPath = "/"; String busName = "org.freedesktop.NetworkManager.Device.Wireless"; boolean ignoreDtd = true; Logger logger = LoggerFactory.getLogger(InterfaceCodeGenerator.class); if (!StringUtils.isBlank(busName)) { String introspectionData = FileIoUtil.readFileToString("src/test/resources/CreateInterface/networkmanager/org.freedesktop.NetworkManager.Device.Wireless.xml"); InterfaceCodeGenerator ci2 = new InterfaceCodeGenerator(introspectionData, objectPath, busName); try { Map<File, String> analyze = ci2.analyze(ignoreDtd); assertEquals(1, analyze.size()); String clzContent = analyze.get(analyze.keySet().iterator().next()); assertTrue(clzContent.contains("@" + DBusInterfaceName.class.getSimpleName() + "(\"" + busName + "\")")); assertFalse(clzContent.contains("this._properties")); assertFalse(clzContent.contains("this._path")); assertFalse(clzContent.contains("this._interfaceName")); } catch (Exception _ex) { logger.error("Error while analyzing introspection data", _ex); } } }
|
ExpectingUnion extends ExpectingOrderBy<RT> { public ExpectingUnion<RT> union(ExpectingUnion<RT> next) { statement.addUnion(next.statement, UnionType.UNION); return this; } ExpectingUnion(SelectStatement<RT> statement); ExpectingUnion<RT> union(ExpectingUnion<RT> next); ExpectingUnion<RT> unionAll(ExpectingUnion<RT> next); }
|
@Test void union() { Database database = testDatabase(new AnsiDialect()); database.select(TypedExpression.value(1), "one") .union(database.select(TypedExpression.literal(2), "two")) .unionAll(database.select(TypedExpression.value(3), "three")) .orderBy(1) .list(transaction); verify(transaction).query(sql.capture(), args.capture(), rowMapper.capture()); assertThat(sql.getValue(), is("select ? as one from DUAL union select 2 as two from DUAL union all select ? as three from DUAL order by 1 asc")); assertThat(args.getValue(), is(toArray(1, 3))); }
|
OptionalUtil extends UtilityClass { public static <T> Optional<T> ofOnly(Iterable<T> iterable) { if (iterable == null) { return Optional.empty(); } return Optional.ofNullable(Iterables.getOnlyElement(iterable, null)); } static Optional<T> ofBlankable(T s); static Optional<T> ofOnly(Iterable<T> iterable); static OptionalWrapper<T> with(Optional<T> optional); static Optional<T> or(Optional<T> optional, Optional<T> other); static Optional<T> orGet(Optional<T> optional, Supplier<? extends Optional<? extends T>> supplier); static Optional<U> as(Class<U> targetClass, Optional<T> source); @SuppressWarnings("unchecked") static Optional<U> as(TypeToken<U> targetType, Optional<T> source); static Optional<U> as(Class<U> targetClass, T source); @SuppressWarnings("unchecked") static Optional<U> as(TypeToken<U> targetType, T source); }
|
@ParameterizedTest @ArgumentsSource(TestCaseArgumentsProvider.class) @TestCase({"null", "empty"}) @TestCase({"", "empty"}) @TestCase({"Some Value", "Some Value"}) void ofOnly(List<String> input, Optional<String> expected) { Optional<String> result = OptionalUtil.ofOnly(input); assertThat(result, is(expected)); }
@Test void ofOnlyWithMultipleThrows() { calling(() -> OptionalUtil.ofOnly(ImmutableList.of("A", "B"))) .shouldThrow(IllegalArgumentException.class) .withMessage("expected one element but was: <A, B>"); }
|
OptionalUtil extends UtilityClass { public static <T> OptionalWrapper<T> with(Optional<T> optional) { return new OptionalWrapper<>(optional); } static Optional<T> ofBlankable(T s); static Optional<T> ofOnly(Iterable<T> iterable); static OptionalWrapper<T> with(Optional<T> optional); static Optional<T> or(Optional<T> optional, Optional<T> other); static Optional<T> orGet(Optional<T> optional, Supplier<? extends Optional<? extends T>> supplier); static Optional<U> as(Class<U> targetClass, Optional<T> source); @SuppressWarnings("unchecked") static Optional<U> as(TypeToken<U> targetType, Optional<T> source); static Optional<U> as(Class<U> targetClass, T source); @SuppressWarnings("unchecked") static Optional<U> as(TypeToken<U> targetType, T source); }
|
@Test void withEmpty() { OptionalUtil.with(Optional.<String>empty()) .ifPresent(consumer) .otherwise(runnable); verify(consumer, never()).accept(any()); verify(runnable, times(1)).run(); }
@Test void withValue() { String value = RandomStringUtils.randomAscii(10); OptionalUtil.with(Optional.of(value)) .ifPresent(consumer) .otherwise(runnable); verify(consumer, times(1)).accept(value); verify(runnable, never()).run(); }
|
OptionalUtil extends UtilityClass { public static <T> Optional<T> or(Optional<T> optional, Optional<T> other) { return optional.isPresent() ? optional : other; } static Optional<T> ofBlankable(T s); static Optional<T> ofOnly(Iterable<T> iterable); static OptionalWrapper<T> with(Optional<T> optional); static Optional<T> or(Optional<T> optional, Optional<T> other); static Optional<T> orGet(Optional<T> optional, Supplier<? extends Optional<? extends T>> supplier); static Optional<U> as(Class<U> targetClass, Optional<T> source); @SuppressWarnings("unchecked") static Optional<U> as(TypeToken<U> targetType, Optional<T> source); static Optional<U> as(Class<U> targetClass, T source); @SuppressWarnings("unchecked") static Optional<U> as(TypeToken<U> targetType, T source); }
|
@ParameterizedTest @ArgumentsSource(TestCaseArgumentsProvider.class) @TestCase({"empty", "empty", "empty"}) @TestCase({"1", "empty", "1"}) @TestCase({"empty", "2", "2"}) @TestCase({"1", "2", "1"}) void or(Optional<Integer> a, Optional<Integer> b, Optional<Integer> expected) { Optional<Integer> result = OptionalUtil.or(a, b); assertThat(result, is(expected)); }
|
OptionalUtil extends UtilityClass { public static <T> Optional<T> orGet(Optional<T> optional, Supplier<? extends Optional<? extends T>> supplier) { return optional.isPresent() ? optional : supplier.get().map(Function.identity()); } static Optional<T> ofBlankable(T s); static Optional<T> ofOnly(Iterable<T> iterable); static OptionalWrapper<T> with(Optional<T> optional); static Optional<T> or(Optional<T> optional, Optional<T> other); static Optional<T> orGet(Optional<T> optional, Supplier<? extends Optional<? extends T>> supplier); static Optional<U> as(Class<U> targetClass, Optional<T> source); @SuppressWarnings("unchecked") static Optional<U> as(TypeToken<U> targetType, Optional<T> source); static Optional<U> as(Class<U> targetClass, T source); @SuppressWarnings("unchecked") static Optional<U> as(TypeToken<U> targetType, T source); }
|
@ParameterizedTest @ArgumentsSource(TestCaseArgumentsProvider.class) @TestCase({"empty", "empty", "empty", "1"}) @TestCase({"123", "empty", "123", "0"}) @TestCase({"empty", "234", "234", "1"}) @TestCase({"123", "234", "123", "0"}) void orGet(Optional<Integer> a, Optional<Integer> b, Optional<Integer> expected, int expectedGets) { if (expectedGets > 0) { when(supplier.get()).thenReturn(b); } Optional<Integer> result = OptionalUtil.orGet(a, supplier); assertThat(result, is(expected)); verify(supplier, times(expectedGets)).get(); }
|
OptionalUtil extends UtilityClass { public static <T, U> Optional<U> as(Class<U> targetClass, Optional<T> source) { return source .filter(v -> targetClass.isAssignableFrom(v.getClass())) .map(targetClass::cast); } static Optional<T> ofBlankable(T s); static Optional<T> ofOnly(Iterable<T> iterable); static OptionalWrapper<T> with(Optional<T> optional); static Optional<T> or(Optional<T> optional, Optional<T> other); static Optional<T> orGet(Optional<T> optional, Supplier<? extends Optional<? extends T>> supplier); static Optional<U> as(Class<U> targetClass, Optional<T> source); @SuppressWarnings("unchecked") static Optional<U> as(TypeToken<U> targetType, Optional<T> source); static Optional<U> as(Class<U> targetClass, T source); @SuppressWarnings("unchecked") static Optional<U> as(TypeToken<U> targetType, T source); }
|
@ParameterizedTest @ArgumentsSource(TestCaseArgumentsProvider.class) @TestCase({"empty", "java.lang.String", "empty"}) @TestCase({"empty", "java.lang.Integer", "empty"}) @TestCase({"empty", "java.lang.Object", "empty"}) @TestCase({"abc", "java.lang.String", "abc"}) @TestCase({"abc", "java.lang.Object", "abc"}) @TestCase({"abc", "java.lang.Integer", "empty"}) void asClass(Optional<String> input, Class<? extends String> target, Optional<String> expected) { Optional<?> result = OptionalUtil.as(target, input); assertThat(result, is(expected)); }
@ParameterizedTest @ArgumentsSource(TestCaseArgumentsProvider.class) @TestCase({"empty", "java.lang.String", "empty"}) @TestCase({"empty", "java.lang.Integer", "empty"}) @TestCase({"empty", "java.lang.Object", "empty"}) @TestCase({"abc", "java.lang.String", "abc"}) @TestCase({"abc", "java.lang.Object", "abc"}) @TestCase({"abc", "java.lang.Integer", "empty"}) void asTypeToken(Optional<String> input, Class<? extends String> target, Optional<String> expected) { Optional<?> result = OptionalUtil.as(TypeToken.of(target), input); assertThat(result, is(expected)); }
@ParameterizedTest @ArgumentsSource(TestCaseArgumentsProvider.class) @TestCase({"null", "java.lang.String", "empty"}) @TestCase({"null", "java.lang.Integer", "empty"}) @TestCase({"null", "java.lang.Object", "empty"}) @TestCase({"abc", "java.lang.String", "abc"}) @TestCase({"abc", "java.lang.Object", "abc"}) @TestCase({"abc", "java.lang.Integer", "empty"}) void asClassWithValue(String input, Class<? extends String> target, Optional<String> expected) { Optional<?> result = OptionalUtil.as(target, input); assertThat(result, is(expected)); }
@ParameterizedTest @ArgumentsSource(TestCaseArgumentsProvider.class) @TestCase({"null", "java.lang.String", "empty"}) @TestCase({"null", "java.lang.Integer", "empty"}) @TestCase({"null", "java.lang.Object", "empty"}) @TestCase({"abc", "java.lang.String", "abc"}) @TestCase({"abc", "java.lang.Object", "abc"}) @TestCase({"abc", "java.lang.Integer", "empty"}) void asTypeTokenWithValue(String input, Class<? extends String> target, Optional<String> expected) { Optional<?> result = OptionalUtil.as(TypeToken.of(target), input); assertThat(result, is(expected)); }
|
SelectStatement { void keepLocks(LockLevel level) { keepLocks = Optional.of(level); } SelectStatement(Scope scope, TypeToken<RT> rowType, From from, RowMapper<RT> rowMapper, Projection projection); TypeToken<RT> rowType(); Stream<CommonTableExpression<?>> commonTableExpressions(); }
|
@ParameterizedTest @ArgumentsSource(TestCaseArgumentsProvider.class) @TestCase({"SHARE", " for read only with rs use and keep SHARE locks"}) @TestCase({"UPDATE", " for read only with rs use and keep UPDATE locks"}) @TestCase({"EXCLUSIVE", " for read only with rs use and keep EXCLUSIVE locks"}) void keepLocks(LockLevel level, String lockSql) { SelectStatement<Integer> sut = new SelectStatement<>(createScope(), TypeToken.of(Integer.class), from, rowMapper, projection); sut.keepLocks(level); when(projection.sql(any())).thenReturn("col1"); when(from.sql(any())).thenReturn(" from tab1"); assertThat(sut.sql(), is("select col1 from tab1" + lockSql)); }
|
Lazy { public Try<T> tryGet() { Try<T> result = value; if (result == null) { synchronized (lock) { result = value; if (result == null) { value = result = Try.trySupply(supplier); } } } return result; } <E extends Exception> Lazy(ThrowingSupplier<T,E> supplier); Try<T> tryGet(); T get(); Optional<T> optional(); Stream<T> stream(); boolean isKnown(); boolean isKnownSuccess(); boolean isKnownFailure(); Lazy<U> map(ThrowingFunction<? super T, ? extends U, E> function); Lazy<U> flatMap(ThrowingFunction<? super T, Lazy<U>, E> function); }
|
@Test void tryGetSuccess() { Lazy<String> sut = new Lazy<>(() -> "Hello World"); Try<String> result = sut.tryGet(); assertThat(result, is(Try.success("Hello World"))); }
@Test void tryGetFailure() { Lazy<String> sut = new Lazy<>(() -> { throw new RuntimeException("Epic fail."); }); Try<String> result = sut.tryGet(); assertThat(result, is(Try.failure(new RuntimeException("Epic fail.")))); }
|
Lazy { public T get() { return tryGet().orElseThrow(); } <E extends Exception> Lazy(ThrowingSupplier<T,E> supplier); Try<T> tryGet(); T get(); Optional<T> optional(); Stream<T> stream(); boolean isKnown(); boolean isKnownSuccess(); boolean isKnownFailure(); Lazy<U> map(ThrowingFunction<? super T, ? extends U, E> function); Lazy<U> flatMap(ThrowingFunction<? super T, Lazy<U>, E> function); }
|
@Test void getSuccess() { Lazy<String> sut = new Lazy<>(() -> "Hello World"); String result = sut.get(); assertThat(result, is("Hello World")); }
@SuppressWarnings("unchecked") @Test void getOnceIfSuccessful() { ThrowingSupplier<String,RuntimeException> supplier = Mockito.mock(ThrowingSupplier.class); when(supplier.get()).thenReturn("Listen very carefully, I shall say this only once."); Lazy<String> sut = new Lazy<>(supplier); String result1 = sut.get(); String result2 = sut.get(); assertThat(result1, is("Listen very carefully, I shall say this only once.")); assertThat(result2, is("Listen very carefully, I shall say this only once.")); verify(supplier, times(1)).get(); }
@SuppressWarnings("unchecked") @Test void getOnlyOnceIfFailed() { ThrowingSupplier<String,RuntimeException> supplier = Mockito.mock(ThrowingSupplier.class); when(supplier.get()).thenThrow(new IllegalArgumentException("Bad argument.")); Lazy<String> sut = new Lazy<>(supplier); calling(sut::get) .shouldThrow(IllegalArgumentException.class) .withMessage("Bad argument."); calling(sut::get) .shouldThrow(IllegalArgumentException.class) .withMessage("Bad argument."); verify(supplier, times(1)).get(); }
|
Lazy { public <U, E extends Exception> Lazy<U> map(ThrowingFunction<? super T, ? extends U, E> function) { return new Lazy<>(() -> tryGet().map(function).orElseThrow()); } <E extends Exception> Lazy(ThrowingSupplier<T,E> supplier); Try<T> tryGet(); T get(); Optional<T> optional(); Stream<T> stream(); boolean isKnown(); boolean isKnownSuccess(); boolean isKnownFailure(); Lazy<U> map(ThrowingFunction<? super T, ? extends U, E> function); Lazy<U> flatMap(ThrowingFunction<? super T, Lazy<U>, E> function); }
|
@Test void mapSuccessFailure() { Lazy<String> sut = new Lazy<>(() -> "Hello"); Lazy<String> map = sut.map(s -> { throw new IllegalArgumentException("Too unfriendly."); }); calling(map::get) .shouldThrow(IllegalArgumentException.class) .withMessage("Too unfriendly."); }
@Test void mapFailure() { Lazy<String> sut = new Lazy<>(() -> { throw new UnsupportedOperationException("No greetings for you."); }); Lazy<String> map = sut.map(s -> s + " World!"); calling(map::get) .shouldThrow(UnsupportedOperationException.class) .withMessage("No greetings for you."); }
|
StringUtil extends UtilityClass { public static String lowercaseFirst(String s) { if (StringUtils.isEmpty(s)) { return ""; } return s.substring(0, 1).toLowerCase() + s.substring(1); } static String lowercaseFirst(String s); static String uppercaseFirst(String s); static String camelToUpper(String camelName); static String hex(byte... bytes); static String octal(byte... bytes); static Function<T,String> prepend(String arg); static Function<T,String> append(String arg); }
|
@ParameterizedTest @ArgumentsSource(TestCaseArgumentsProvider.class) @TestCase({"null", ""}) @TestCase({"", ""}) @TestCase({"a", "a"}) @TestCase({"B", "b"}) @TestCase({"abc", "abc"}) @TestCase({"ABC", "aBC"}) @TestCase({" DEF", " DEF"}) void lowercaseFirst(String input, String expected) { assertThat(StringUtil.lowercaseFirst(input), is(expected)); }
|
StringUtil extends UtilityClass { public static String uppercaseFirst(String s) { if (StringUtils.isEmpty(s)) { return ""; } return s.substring(0, 1).toUpperCase() + s.substring(1); } static String lowercaseFirst(String s); static String uppercaseFirst(String s); static String camelToUpper(String camelName); static String hex(byte... bytes); static String octal(byte... bytes); static Function<T,String> prepend(String arg); static Function<T,String> append(String arg); }
|
@ParameterizedTest @ArgumentsSource(TestCaseArgumentsProvider.class) @TestCase({"null", ""}) @TestCase({"", ""}) @TestCase({"a", "A"}) @TestCase({"B", "B"}) @TestCase({"abc", "Abc"}) @TestCase({" def", " def"}) void uppercaseFirst(String input, String expected) { assertThat(StringUtil.uppercaseFirst(input), is(expected)); }
|
StringUtil extends UtilityClass { public static String camelToUpper(String camelName) { if (StringUtils.isEmpty(camelName)) { return ""; } return Arrays.stream(camelName.split("(?<!(^|[A-Z]))(?=[A-Z])|(?<!^)(?=[A-Z][a-z])")) .filter(StringUtils::isNotBlank) .map(String::toUpperCase) .collect(joining("_")); } static String lowercaseFirst(String s); static String uppercaseFirst(String s); static String camelToUpper(String camelName); static String hex(byte... bytes); static String octal(byte... bytes); static Function<T,String> prepend(String arg); static Function<T,String> append(String arg); }
|
@ParameterizedTest @ArgumentsSource(TestCaseArgumentsProvider.class) @NullValue("<NULL>") @TestCase({"<NULL>", ""}) @TestCase({"", ""}) @TestCase({"a", "A"}) @TestCase({"B", "B"}) @TestCase({"abc", "ABC"}) @TestCase({" def", " DEF"}) @TestCase({"aBC", "A_BC"}) @TestCase({"camelCase", "CAMEL_CASE"}) @TestCase({"camelCaseWithTLA", "CAMEL_CASE_WITH_TLA"}) @TestCase({"camelCaseWithTLAInMiddle", "CAMEL_CASE_WITH_TLA_IN_MIDDLE"}) @TestCase({"tlaAtStart", "TLA_AT_START"}) @TestCase({"NotCamelCase", "NOT_CAMEL_CASE"}) @TestCase({"TLANotCamelCase", "TLA_NOT_CAMEL_CASE"}) void camelToUpper(String input, String expectedResult) { assertThat(StringUtil.camelToUpper(input), is(expectedResult)); }
|
SelectStatement { From from() { return from; } SelectStatement(Scope scope, TypeToken<RT> rowType, From from, RowMapper<RT> rowMapper, Projection projection); TypeToken<RT> rowType(); Stream<CommonTableExpression<?>> commonTableExpressions(); }
|
@Test void from() { SelectStatement<Integer> sut = new SelectStatement<>(createScope(), TypeToken.of(Integer.class), from, rowMapper, projection); From result = sut.from(); assertThat(result, sameInstance(from)); }
|
StringUtil extends UtilityClass { public static String hex(byte... bytes) { if (bytes == null) { return ""; } StringBuilder builder = new StringBuilder(bytes.length * 2); for (byte b : bytes) { builder.append(String.format("%02x", b)); } return builder.toString(); } static String lowercaseFirst(String s); static String uppercaseFirst(String s); static String camelToUpper(String camelName); static String hex(byte... bytes); static String octal(byte... bytes); static Function<T,String> prepend(String arg); static Function<T,String> append(String arg); }
|
@ParameterizedTest @ArgumentsSource(TestCaseArgumentsProvider.class) @TestCase({"null", ""}) @TestCase({"", ""}) @TestCase({"-128", "80"}) @TestCase({"-1", "ff"}) @TestCase({"0", "00"}) @TestCase({"15", "0f"}) @TestCase({"127", "7f"}) @TestCase({"0, 127, 10", "007f0a"}) @TestCase({"0xde,0xad,0xbe,0xef", "deadbeef"}) void hex(byte[] input, String expectedResult) { assertThat(StringUtil.hex(input), is(expectedResult)); }
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.