Proper Javadoc example / add test for StringUtils

- Proper example for the purpose of javadoc and how it could look like
- Fix containsAny to be null safe
- Add tests
This commit is contained in:
ljacqu 2015-11-21 08:28:53 +01:00
parent 38cc217cff
commit 9a68aa5517
2 changed files with 61 additions and 11 deletions

View File

@ -5,17 +5,18 @@ import net.ricecode.similarity.StringSimilarityService;
import net.ricecode.similarity.StringSimilarityServiceImpl;
/**
* Utility class for String operations.
*/
public class StringUtils {
/**
* Get the difference of two strings.
*
* @param first First string.
* @param second Second string.
* @param first First string
* @param second Second string
*
* @return The difference value. */
* @return The difference value
*/
public static double getDifference(String first, String second) {
// Make sure the strings are valid.
if(first == null || second == null)
@ -27,22 +28,25 @@ public class StringUtils {
// Determine the difference value, return the result
return Math.abs(service.score(first, second) - 1.0);
}
/**
* Method containsAny.
* @param str String
* @param pieces String[]
* @return boolean */
* Returns whether the given string contains any of the provided elements.
*
* @param str the string to analyze
* @param pieces the items to check the string for
*
* @return true if the string contains at least one of the items
*/
public static boolean containsAny(String str, String... pieces) {
if (str == null) {
return false;
}
for (String piece : pieces) {
if (str.contains(piece)) {
if (piece != null && str.contains(piece)) {
return true;
}
}
return false;
}
}

View File

@ -0,0 +1,46 @@
package fr.xephi.authme.util;
import org.junit.Test;
import static org.hamcrest.Matchers.equalTo;
import static org.junit.Assert.assertThat;
/**
* Test for {@link StringUtils}.
*/
public class StringUtilsTest {
@Test
public void shouldFindContainedItem() {
// given
String text = "This is a test of containsAny()";
String piece = "test";
// when
boolean result = StringUtils.containsAny(text, "some", "words", "that", "do not", "exist", piece);
// then
assertThat(result, equalTo(true));
}
@Test
public void shouldReturnFalseIfNoneFound() {
// given
String text = "This is a test string";
// when
boolean result = StringUtils.containsAny(text, "some", "other", "words", null);
// then
assertThat(result, equalTo(false));
}
@Test
public void shouldReturnFalseForNullString() {
// given/when
boolean result = StringUtils.containsAny(null, "some", "words", "to", "check");
// then
assertThat(result, equalTo(false));
}
}