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(part)); return allList.toArray(new String[allList.size()]); }
private String[] getRandomComments() { String[] comments = new String[RandomUtils.nextInt(10)]; for (int i = 0; i < comments.length; i++) { String comment = RandomStringUtils.randomAlphabetic(5); String keyword = RandomUtils.nextBoolean() ? getKeywords()[RandomUtils .nextInt(getKeywords().length)] : ""; comment += keyword + RandomStringUtils.randomAlphabetic(5); comments[i] = comment; } return comments; }
private String[] getKeywords() { String[] keywords = new String[] { "X", "XX", "XXX", "XXXX", "XXXXX", "XXXXXX", "XXXXXXX" }; return keywords; }
} |