Assert the String has certain length (Java) - java

Is there any way to assert in a method that input String has certain length?
I tried assert stringName[4]; but seems like it doesn't work

If you just want to use the Java's assert keyword and not any library like JUnit, then you can probably use:
String myStr = "hello";
assert myStr.length() == 5 : "String length is incorrect";
From the official docs:
The assertion statement has two forms. The first, simpler form is:
assert Expression1;
where Expression1 is a boolean expression. When
the system runs the assertion, it evaluates Expression1 and if it is
false throws an AssertionError with no detail message.
The second form of the assertion statement is:
assert Expression1 : Expression2 ;
where:
Expression1 is a boolean expression. Expression2 is an expression that
has a value. (It cannot be an invocation of a method that is declared
void.)
You can use the following if you're using a testing library like JUnit:
String myStr = "hello";
assertEquals(5, myStr.length());
Update:
As correctly pointed out in the comments by AxelH, after compilation, you run the first solution as java -ea AssertionTest. The -ea flag enables assertions.

Instead of using assert, I'd recommend using Exception to check the state of the variables as a simple demo:
String[] arr = new String[3];
if (arr.length != 4) {
throw new IllegalStateException("Array length is not expected");
}
This will directly give the hint by exceptions and you don't need to bother with assert in jvm options.
Exception in thread "main" java.lang.IllegalStateException: Array length is not expected
at basic.AssertListLength.main(AssertListLength.java:7)

If you are using hamcrest, then you can do:
assertThat("text", hasLength(4))
See http://hamcrest.org/JavaHamcrest/javadoc/2.2/ > CharSequenceLength
Good thing about this is that it will have a proper error message, among others including the string itself.

Use AssertJ hasSize():
assertThat(stringName).hasSize(4)

Related

jsqlparser to evaluate a condition

The following String:
x=92 and y=29
Produces a valid output: x=92 AND y=29 and it works fine with CCJSqlParserUtil.parseCondExpression but shouldn't it throw an exception for the following?
x=92 lasd y=29
But the output is just: x=92
Furthermore which Expression I should use to implement my own visitor? i.e,
CCJSqlParser c= new CCJSqlParser(new StringReader(str));
Expression e = c.Expression(); // or SimpleExpression, etc..
So that when 'lasd' (anything other than not,or,and) is encountered I can throw an exception and not silently ignore the rest of the expression?
Recently a patch of JSqlParser (1.2-SNAPSHOT) was published to provide the needed behaviour:
CCJSqlParserUtil.parseExpression(String expression, boolean allowPartialParse)
and
CCJSqlParserUtil.parseCondExpression(String expression, boolean allowPartialParse)
Setting allowPartialParse to false will result in the mentioned Exception.
For on the fly interpreted stuff the already existing behaviour is still needed, e.g. to provide expressions from within an text. (Syntax coloring, Context help, ...)

Find List of String which mache in Text using Regex

I am getting stuck in this situation.
public void findListOfPattern(){
String text = "abce1213abcd231asdf";
String find = "1213|231|1232";
Pattern part = Pattern.compile(find);
Matcher mat = part.matcher(text);
System.out.println(mat.find()); //True
}
Able to get true result if any of string in find get match.
I want list of matcher from text.
There text can large with more find string and also find string can more.
In find : 1213,231,1232 are separates.
Result should be like :- 1213,231
You need to invoke mat.group() to return the desired match.
Typically you'd loop until mat.find() returns true and print all matches successively by invoking mat.group().
You can then build your expected result String by concatenating the outcome of mat.group() as you wish, e.g. with a StringBuilder.
Notes
API here.
You need to invoke Matcher#find in order for Matcher#group to yield any result and not throw IllegalStateException
Your Pattern only has the default group. If you'd used parenthesis or named groups (from Java 7), you could also invoke overloads Matcher#group(int group) or Matcher#group(String name).

Assertion issue in Java and Eclipse

I am using Java, Selenium Webdriver and Junit. Doing simple verification of title of Google , But it throws exception when Assertion fails I mean when title does not match.
Code :
public static void verifyTitle(String expectedTitle) {
//get the title of the page
String actualTitle = Base.getdriver().getTitle();
// verify title
assertThat(actualTitle, equalTo(expectedTitle));
}
I am calling in main method : verifyTitle("Hello");
Output :
> Exception in thread "main" java.lang.AssertionError: Expected:
> "Hello"
> but: was "Google" at org.hamcrest.MatcherAssert.assertThat(MatcherAssert.java:20) at
> org.junit.Assert.assertThat(Assert.java:956) at
> org.junit.Assert.assertThat(Assert.java:923) at
> Modules.Help.verifyTitle(Help.java:161) at
> Modules.Help.GUI(Help.java:152) at Modules.Help.main(Help.java:29)
It is checking everything proper but not sure why throwing exception? How can I print message like "Title does not match" instead of this exception.
Write this:
if (!Objects.equals(actualTitle, expectedTitle))
System.out.println("Title doesn't match.");
But why would you want to do that?
Selenium tests inform you when something is not as expected, automatically. Throwing an AssertError means failure, and that failure can be displayed nicely to humans. When you use System.out.println, you just print something, but the program continues as if there were no error.
That is expected behavior of JNunit! It will always throw exception when assert failed. Here is description of the method assertThat:
Asserts that actual satisfies the condition specified by matcher. If
not, an AssertionError is thrown with information about the matcher
and failing value.
You can try/catch the Error then print the message that you want.
try {
assertThat("a", equalTo("a"));
System.out.println("Title matched");
}
catch(Error e) {
System.out.println("Title does not match");
}
You should try the try catch, have a look here: http://beginnersbook.com/2013/04/try-catch-in-java/ I think it could help you ;)
Just study the javadoc for assertThat:
Asserts that actual satisfies the condition specified by matcher. If not, an AssertionError is thrown with information about the matcher and failing value.
The point is that when you are running with JUnit, the exception is catched; and translated to some nice printout. So, when you are working outside of a JUnit #Test; well; then some other code needs to try/catch ...

Check if a string ends in is valid or not in java using regex

I have the following requirement where in I need to do few things only if the given string ends in "Y" or "Years" or "YEARS".
I tried doing it using regex like this.
String text=1.5Y;
if(Pattern.matches("Y$",text) || Pattern.matches("YEARS$",text) || Pattern.matches("Years",text))
{
//do
}
However this is getting failed.
Can someone point me where I have gone wrong or suggest me any other feasible method.
EDIT:
Thanks.That helps.
Finally I have used "(?i)^.*Y(ears)?$| (?i)^.*M(onths)?$".
But I want to make more changes to make it perfect.
Let's say I have many strings.
Ideally only strings like 1.5Y or 0.5-3.5Y or 2.5/2.5-4.5Y should pass if check.
It can be number of years(Ex:2.5y) or the period of years(2.5-3.5y) or the no of years/period of years(Ex.2.5/3.5-4.5Y) nothing more.
More Examples:
--------------
Y -should fail;
MY - should fail;
1.5CY - should fail;
1.5Y-2.5Y should fail;
1.5-2.5Y should pass;
1.5Y/2.5-3.5Y should fail;
1.5/2.5-3.5Y should pass;
You don't need a regex here:
if(text.endsWith("Y") || ...)
matches method attempts to match full input so use:
^.*Y$
for your first pattern.
btw you can use a single regex for all 3 cases:
if (text.matches( "(?i)^.*Y(ears)?$" ) ) {...}
(?i) does ignore case match.
.*(?:Y|YEARS|Years)$
You can directly use this .Match matches from beginning.So yours is failing.
You can simply use the regex pattern:
if (Pattern.matches(".*(Y|YEARS|Years)$",text)) {/*do something*/}
/((?!0)\d+|0)(.\d+)?(?:years|year|y)/gi
https://regex101.com/r/gJ6xD2/2
var text = "1.6y 1.5years 1year 1.5h";
text.match(/((?!0)\d+|0)(\.\d+)?(?:years|year|y)/gi);
Result["1.6y", "1.5years", "1year"]
(?=^(0\.\d+|[1-9](?:\d+)?(?:\.\d+)?)(?:(\s+)?[\/-](\s+)?(?:0\.\d+|[1-9](?:\d+)?(?:\.\d+)?))*(?:\s+)?(?:y(?:(ea)?rs|ears?)?|m(?:onths?)?)$).*
https://regex101.com/r/kL7rQ1/3
Only thing I wasn't sure "2.3 - 4 / 6.2 y" format is acceptable or not, so I've included it.

Java: Question on assert-behaviour

I have this code snippet
import java.util.ArrayList;
import java.util.List;
public class AssertTest {
public static void main(String[] args) {
List<String> list = new ArrayList<String>();
assert(list.add("test")); //<-- adds an element
System.out.println(list.size());
}
}
Output:
0
Why is the output list empty? How does assert behave here?
Thank you in advance!
You should enable assertion with -ea flag... such as;
java -ea -cp . AssertTest
Also using assertion is worst place for side effects..
Never assert on anything with side effects. When you run without asserts enabled (enabled with -ea), list.add("test") will not be executed.
It's a good habit to never assert anything but false, as follows:
if (!list.add("test")) {
assert false;
// Handle the problem
}
you have to enable assert. ie run as java -ea AssertTest
Incidental to your question - assertions should not contain code that is needed for the correct operation of your program, since this causes that correct operation to be dependent on whether assertions are enabled or not.
Assertions needs to be enabled. Enable them using the -ea switch.
See the Java application launcher docs.
assert method that checks whether a Boolean expression is true or false. If the expression evaluates to true, then there is no effect. But if it evaluates to false, the assert method prints the stack trace and the program aborts. In this sample implementation, a second argument for a string is used so that the cause of error can be printed.

Categories