public void ClaimValidation() {
float validateMemberPay = S3_1Response.jsonPath().get("planCopayAmount");
softAssert.assertEquals(validateMemberPay, 300.00);
float validatePlanPay = S3_1Response.jsonPath().get("planPayAmount");
softAssert.assertEquals(validatePlanPay, 800.00, assertionMessage);
softAssert.AssertAll();
expected [300.0] but found [300.0],
ASSERTION HAS FAILED expected [800.0] but found [800.0]
Related
This code needs to be tested but I'm not able to resolve the error.
Boolean isValid is the method which needs to be tested.
public boolean isValid(String email)
{
String emailRegex = "^[a-zA-Z0-9_+&*-]+(?:\\."+
"[a-zA-Z0-9_+&*-]+)*#" +
"(?:[a-zA-Z0-9-]+\\.)+[a-z" +
"A-Z]{2,7}$";
Pattern pat = Pattern.compile(emailRegex);
if (email == null)
return false;
return pat.matcher(email).matches();
}
Getting error in writing test case: Cannot invoke isEqualTo(boolean) on the primitive type boolean
#Test
public void isValidTest() {
Validation v = new Validation();
String email = "bhavya#gmail.com";
assertEquals(v.isValid(email).isEqualTo(true)); //this line gives the error.
}
assertEquals(v.isValid(email).isEqualTo(true);
This line is wrong in so many ways.
The parentheses don't even line up.
The isEqualTo thing does not start with assertEquals - it starts with assertThat. You're mixing two completely different ways to write tests.
Because of the missing parens, you are now attempting to invoke .isEqualTo on a primitive boolean. It's not an object, primitiveExpression.anything doesn't work in java.
You presumably want either:
assertThat(v.isValid(email)).isEqualTo(true);
or more likely:
assertTrue(v.isValid(email));
//you can try is it with assertTrue and pass the value type return by isValid()
#Test
public void isValidTest() {
Validation v = new Validation();
String email = "bhavya#gmail.com";
Boolean value = v.isValid(email);
assertTrue(value);
}
I go over the all build-in exception in JDK, I only find SizeLimitExceededException when size exceed the expected length. However, if I want to throw an exception when size limit is below the expected length, there is no such built-in exception class that I can call?
Update:
SSN is 9 digits length. If input SSN is shorter than 9 digits length, then I want to throw this exception.
While using a fitting exception is good practice and you should spend some time to look for a fitting one (as you did), there is usually also no need to go over board with it.
In your example, I'd consider it totally fine if you'd just throw an new IllegalArgumentException("SSN is only of length <X> but length 9 is required"). It will fail the execution and give you a meaningful stacktrace.
Be aware that it is considered bad practice to use exception for control flow. So please never ever use something like
try {
person.setSSN(ssn);
catch (SSNTooShortException e) {
println("SSN too short! Please try again");
}
Instead use a custom validator to check SSN before setting it and only use the exception to guard against programming error.
if (!SSNFormat.matches(ssn)) { // <-- whoops condition is inverted
person.setSSN(ssn);
}
This snippet will hopefully fail soon in your (unit) test and you will know that your programming logic is flawed.
Of course, depending of your application, instead of using your custom validator, you could and should use one of the many validator frameworks (for an example, look at Hibernate's constraints, but virtually all big frameworks support validation in one or the other form).
Suppose there was a built-in JDK SizeLimitSubceededException (I just learned that subceeded is the opposite of exceeded). Would your code, which checks the length of the SSN throw one exception - SizeLimitExceededException - if the size exceeds the expected size, and another exception - SizeLimitSubceededException - if the size subceeds the expected size?
This would be awkward:
You would have to specify both exceptions in the throws clause of your method (assuming SizeLimitSubceededException would be a checked exception, same as SizeLimitExceededException).
The caller of your method would have to handle both exceptions.
And what if the size is right, but something else is wrong - for example, the SNN contains non-digit characters? Would you throw a third exception for that?
My point is that you'd be better off throwing a single type of exception from the method that sets the SSN.
If you want this to be a checked exception (which I suggest, in order to force the caller to handle it), I suggest defining your own custom exception - perhaps InvalidSSNException. This exception can have a constructor with several arguments - one of them the invalid SSN, another could be a boolean that indicates if the exception was thrown due to incorrect length.
Then your custom exception can produce an error message that matches the reason to the failure:
If the entered SSN had the wrong length (and it doesn't matter if it's too long or too short), the message would specify the expected length (9).
If the entered SSN had the correct length, the message would specify the valid characters (digits only).
Example:
class Person {
...
public setSSN (String ssn) throws InvalidSSNException
{
if (ssn == null) {
throw new InvalidSSNException (ssn, false);
}
if (ssn.length() != 9) {
// exception thrown as a result of invalid length
throw new InvalidSSNException (ssn, true);
}
for (char c : ssn.toCharArray()) {
if (c < '0' || c > '9') {
// exception thrown as a result of invalid character
throw new InvalidSSNException (ssn, false);
}
}
this.ssn = ssn;
}
...
}
Maybe you want something like IndexOutOfBoundsException. It is thrown to indicate that an index of some sort of data is out of range.
https://docs.oracle.com/javase/7/docs/api/java/lang/IndexOutOfBoundsException.html
You can create an exception as
public class UnderBottomException extends Exception {
public UnderBottomException(int dim, int param) {
super();
System.out.println("you entered a length of : " + dim + " whereas the minimum length expected is : " + param);
}
}
This exception will be implementable this way in your POJO :
public class Register {
private int[] registre;
private int minRange = 9;
public Register(int[] parametre) throws UnderBottomException {
if (parametre.length < this.minRange) {
throw new UnderBottomException(parametre.length, this.minRange);
}
else {
this.registre = new int[parametre.length];
for (int i = 0 ; i < this.registre.length; i++)
this.registre[i] = parametre[i];
}
}
public int[] getRegistre() {
return registre;
}
public int getMinRange() {
return minRange;
}
}
And finaly you use your object catching exception like this :
public class Main {
public static void main(String[] args) {
int[] a = {1,2,3,4,5,6,7,8};
try {
Register monRegistre = new Register(a);
System.out.println("Nickel le sous registre de rang 2 = " + monRegistre.getRegistre()[1]);
}
catch(UnderBottomException e) {
}
}
}
Output :
you entered a length of : 8 whereas the minimum length expected is : 9
I am trying to write a tester class to test a file that has already been compiled. I am basically trying to see if the coordinates of are correct when rotated 90 degrees. I am not really sure how to write a tester class. ANy advice on how to do this?
public static void testRotate90(){
int fails = SUnit.testsFailed();
System.out.println ("Testing Rotate 90...");
CartesianPoint cp = new CartesianPoint();
CartesianPoint cp2 = cp.rotate90();
if (fails == SUnit.testsFailed())
System.out.println(" PASS");
}
You should use asserts to compare what you expect the result to be to the actual result. A test fails as a result of either an invalid assertion or calling the fail() method (for instance if you expect an exception to be thrown you might put a call to fail on the line that should not be reached).
You don't have to worry about producing output for the test, the test framework will record what assertions failed for which test class.
Let's say your CartesianPoint class looks like:
public class CartesianPoint {
private final long x;
private final long y;
public CartesianPoint(long x, long y) {
this.x = x; this.y = y;
}
public CartesianPoint rotate90() {
// actual logic omitted, hardcoding result
return new CartesianPoint(0, 1);
}
public long getX() {return x;}
public long getY() {return y;}
}
Then if you expect to create a point with x = 1 and y = 0 and rotate it to get x = 0 and y = 1, the test could look like:
public class SomeTest {
public void testRotate90(){
CartesianPoint cp = new CartesianPoint(1,0);
CartesianPoint cp2 = cp.rotate90();
SUnit.assertEquals(0, cp2.getX());
SUnit.assertEquals(1, cp2.getY());
}
}
For cases like this you may want to test using a number of different inputs, see this question for an example of how to write a parameterized test using JUnit.
How can I use the 'unique' method in the TotallyLazy library for Java and Objective-C?
I have the following code, but I cannot complete it because I'm not sure how the Callable1 instance passed into 'unique' should be composed. Here's what I have so far:
seq
.sort(new Comparator<T>() {
#Override
public int compare(
final T pt1,
final T pt2
) {
return pt1.compareTo(pt2);
}
})
.unique(new Callable1<T,T>() {
#Override
public T call(final T pt) throws Exception {
final int result = pt.compareTo(..?);
return result != 0;
}});
As you can see, I can sort successfully, but when it comes to "result = ..." in the 'unique' call, what should I put?
Firstly for sorting you should probably use one of the provided Comparators:
seq.sort(Comparators.<T>ascending());
Then you could just unique with no arguments if uniqueness is based on equality of T as a whole. The overload for unique allows one to get a unique sequence based on some property of T.
For example if you had a Sequence<User> you could say I want them to be unique based on their firstName field:
class User {
String firstName, lastName;
User(...){...} // Constructor
}
sequence(new User("Chris", "Nash")).unique(user -> user.firstName)
TotallyLazy has extensive Tests that document the features but the first place to start would always be the SequenceTest or have a look in the whole test package for more examples.
There are some situation that I need to convert string to float or some other numerical data-type but there is a probability of getting some nonconvertible values such as "-" or "/" and I can't verify all the values beforehand to remove them.
and I want to avoid using try/catch for this matter , is there any other way of doing a proper conversion in java? something similar to C# TryParse?
The simplest thing I can think of is java.util.Scanner . However this approach requires a new Scanner instance for each String.
String data = ...;
Scanner n = new Scanner(data);
if(n.hasNextInt()){//check if the next chars are integer
int i = n.nextInt();
}else{
}
Next you could write a regex pattern that you use to check the String (complex to fail too big values) and then call Integer.parseInt() after checking the string against it.
Pattern p = Pattern.compile("insert regex to test string here");
String data = ...;
Matcher m = p.matcher(data);
//warning depending on regex used this may
//only check part of the string
if(m.matches()){
int i = Integer.parseInt(data);
}
However both of these parse the string twice, once to test the string and a second time to get the value. Depending on how often you get invalid strings catching an exception may be faster.
Unfortunately, there is no such method in Java. There is no out parameter in Java, so writing such a method would need to return a null Float to signal an error, or to pass a FloatHolder object which could be modified by the method:
public class FloatHolder {
private float value;
public void setValue(float value) {
this.value = value;
}
public float getValue() {
return this.value;
}
}
public static boolean tryParseFloat(String s, FloatHolder holder) {
try {
float value = Float.parseFloat(s);
holder.setValue(value);
}
catch (NumberFormatException e) {
return false;
}
}
This is an old question, but since all the answers fail to mention this (and I wasn't aware of it myself until seeing it in a merge request written by a colleague), I want to point potential readers to the Guava Floats and Ints classes:
With the help of these classes, you can write code like this:
Integer i = Ints.tryParse("10");
Integer j = Ints.tryParse("invalid");
Float f = Floats.tryParse("10.1");
Float g = Floats.tryParse("invalid.value");
The result will be null if the value is an invalid int or float, and you can then handle it in any way you like. (Be careful to not just cast it to an int/float, since this will trigger a NullPointerException if the value is an invalid integer/floating point value.)
Note that these methods are marked as "beta", but they are quite useful anyway and we use them in production.
For reference, here are the Javadocs for these classes:
https://google.github.io/guava/releases/snapshot-jre/api/docs/com/google/common/primitives/Ints.html
https://google.github.io/guava/releases/snapshot-jre/api/docs/com/google/common/primitives/Floats.html
Java does not provide some built in tryParse type of methods, on of the solutions you can try is to create your own tryParse Method and put try/catch code in this method and then you can easily use this method across your application very easily and without using try/catch at all the places you use the method.
One of the sample functions can have following code
public static Long parseLong(String value) {
if(isNullOrEmpty(value)) {
return null;
}
try {
return Long.valueOf(value);
}
catch (NumberFormatException e) {
}
return null;
}
Regular expressions helped me solve this issue. Here is how:
Get the string input.
Use the expression that matches one or more digits.
Parse if it is a match.
String s = "1111";
int i = s.matches("^[0-9]+$") ? Integer.parseInt(s) : -1;
if(i != -1)
System.out.println("Integer");
else
System.out.println("Not an integer");