用Ruby简化你的Java测试(4)
时间:2011-01-27 infoq 殷安平
其中,有两点需要注意,首先,我们可以通过to_java方法将Ruby类型转换成Java类型,例如上面将@keywords.to_java :String表明将Ruby数组转换成Java的String数组。第二,Ruby对数组支持“-”的操作,表示将一个数组减去和另一个数组中相同的元素,非常的直观!很明显,被过滤的数组应该等于原来的数组减去过滤后的结果!运行mvn test,我们将看到
[INFO] [jtestr:test {execution: default}]
Other TestUnit: 2 tests, 0 failures, 0 errors 结论
说明新增加的测试通过!最后我们来对比一下实现同样的功能Ruby和Java的差别
Ruby:
require ''test/unit''
import ''com.alisoft.research.JRuby.service.KeywordFilterServiceImpl''
class KeywordFilterServiceTest < Test::Unit::TestCase
def setup
@keywords = %w{X XX XXX XXXX XXXXX XXXXXX XXXXXXX}
end
def test_filter
comments = random_comments
service = KeywordFilterServiceImpl.new(@keywords.to_java :String)
filted = service.filter(comments.to_java :String)
forbiddens = service.getFiltedComments
assert forbiddens.length == comments.length - filted.length
assert_equal forbiddens.sort, (comments - filted).sort
end
def random_alphabetic(size=5)
chars = (''a''..''z'').to_a + (''A''..''Z'').to_a
(0...size).collect { chars[rand(chars.length)] }.join
end
def random_comments
comments ||= []
10.times do
keyword = rand(10) % 3 == 0 ? '' '' : @keywords[rand(@keywords.length)]
comment = random_alphabetic + keyword + random_alphabetic
comments << comment
end
return comments
end
end
Java:
package com.alisoft.research.JRuby.test;
import static org.junit.Assert.assertArrayEquals;
import static org.junit.Assert.assertEquals;
import Java.util.ArrayList;
import Java.util.Arrays;
import Java.util.List;
import org.apache.commons.lang.RandomStringUtils;
import org.apache.commons.lang.math.RandomUtils;
import org.junit.Test;
import com.alisoft.research.JRuby.service.KeywordFilterServiceImpl;
public class KeywordFilterServiceTest {
@Test
public void testFilteredResults() {
String[] comments = getRandomComments();
KeywordFilterServiceImpl service = new KeywordFilterServiceImpl(
getKeywords());
String[] filted = service.filter(comments);
String[] forbiddens = service.getFiltedComments();
assertEquals(filted.length + forbiddens.length, comments.length);
assertArrayEquals(forbiddens, sub(comments, filted));
}
//实现减法操作
private String[] sub(String[] all, String[] part) {
List allList = new ArrayList(Arrays.asList(all));
allList.removeAll(Arrays.asList(p
|