import cn.edu.mju.project1.controller.CaptcheController;import org.junit.Test;publicclassTestCaptche{@TestpublicvoidtestRandomString(){CaptcheController c =newCaptcheController();System.out.println(c.ranString(4));}}
這個代碼可以測試CaptcheController中的ranString方法。
public String ranString(int count){//定義方法,返回字符串 public對比private 在類外也可以訪問StringBuilder builder =newStringBuilder();String str ="abcdefghijklmnpqrstuvwxy01234567890";//z,o不推薦用,容易和數字0,2混淆Random rnd =newRandom();//生成隨機變量for(int i =0;i<count;i++){//可以隨機生成4個變量 count為傳入的參數int pos = rnd.nextInt(str.length());//得到str的位置String s = str.substring(pos,pos+1);//0-19,取一個builder.append(s);}return builder.toString();//返回}