Skip to content

Commit

Permalink
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Use assertThrows
Browse files Browse the repository at this point in the history
Replace fail with assertThrows in serveral places
marschall committed Dec 1, 2023

Verified

This commit was created on GitHub.com and signed with GitHub’s verified signature. The key has expired.
1 parent db56a3b commit 3c65dbd
Showing 16 changed files with 70 additions and 181 deletions.
15 changes: 0 additions & 15 deletions src/test/java/org/eclipse/yasson/Assertions.java
Original file line number Diff line number Diff line change
@@ -21,21 +21,6 @@

public class Assertions {

/**
* Asserts that the given operation will fail with a JsonbException
* @param operation The operation that is expected to fail
*/
public static void shouldFail(Supplier<?> operation) {
shouldFail(operation, JsonbException.class, msg -> true);
}

public static void shouldFail(Runnable operation) {
shouldFail(() -> {
operation.run();
return null;
});
}

/**
* Asserts that the given operation will fail with a JsonbException
* @param operation The operation that is expected to fail
9 changes: 2 additions & 7 deletions src/test/java/org/eclipse/yasson/Issue456Test.java
Original file line number Diff line number Diff line change
@@ -12,7 +12,7 @@

package org.eclipse.yasson;

import static org.junit.jupiter.api.Assertions.fail;
import static org.junit.jupiter.api.Assertions.assertThrows;

import org.junit.jupiter.api.Test;

@@ -23,12 +23,7 @@ public class Issue456Test {

@Test
public void dontInvokeToString() {
try {
JsonbBuilder.create().toJson(new Example());
fail("JsonbException is expected");
} catch (JsonbException e) {
// Expected
}
assertThrows(JsonbException.class, () -> JsonbBuilder.create().toJson(new Example()));
}

public static class Example {
9 changes: 3 additions & 6 deletions src/test/java/org/eclipse/yasson/JavaxNamingExcludedTest.java
Original file line number Diff line number Diff line change
@@ -29,13 +29,10 @@ public class JavaxNamingExcludedTest {

@Test
public void testNoJavaxNamingModule() {
try {
Class.forName(JsonbComponentInstanceCreatorFactory.INITIAL_CONTEXT_CLASS);
fail("Class [" + JsonbComponentInstanceCreatorFactory.INITIAL_CONTEXT_CLASS
//OK, java.naming is not observable
assertThrows(ClassNotFoundException.class, () -> Class.forName(JsonbComponentInstanceCreatorFactory.INITIAL_CONTEXT_CLASS),
() -> "Class [" + JsonbComponentInstanceCreatorFactory.INITIAL_CONTEXT_CLASS
+ "] should not be available for this test.");
} catch (ClassNotFoundException e) {
//OK, java.naming is not observable
}

final String result = defaultJsonb.toJson(new AdaptedPojo());
assertEquals("{\"adaptedValue1\":1111,\"adaptedValue2\":1001,\"adaptedValue3\":1010}", result);
Original file line number Diff line number Diff line change
@@ -63,13 +63,9 @@ public static class AnnotatedPojo<T,X> {
public void testIncompatibleAdapter() throws Exception {
IncompatibleAdapterPojo incompatibleAdapterFieldPojo = new IncompatibleAdapterPojo();
incompatibleAdapterFieldPojo.str = "STR";
try {
defaultJsonb.toJson(incompatibleAdapterFieldPojo);
fail();
} catch (JsonbException e) {
assertTrue(e.getMessage().startsWith("Adapter of runtime type class"));
assertTrue(e.getMessage().contains("does not match property type "));
}
JsonbException e = assertThrows(JsonbException.class, () -> defaultJsonb.toJson(incompatibleAdapterFieldPojo));
assertTrue(e.getMessage().startsWith("Adapter of runtime type class"));
assertTrue(e.getMessage().contains("does not match property type "));
}

@Test
Original file line number Diff line number Diff line change
@@ -39,7 +39,6 @@
import static org.junit.jupiter.api.Assertions.assertNull;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.junit.jupiter.api.Assertions.fail;

/**
* @author Roman Grigoriadi
@@ -79,22 +78,14 @@ public void testRootCreatorWithInnerCreator() {

@Test
public void testIncompatibleFactoryMethodReturnType() {
try {
defaultJsonb.fromJson("{\"s1\":\"abc\"}", CreatorIncompatibleTypePojo.class);
fail();
} catch (JsonbException e) {
assertTrue(e.getMessage().startsWith("Return type of creator"));
}
JsonbException e = assertThrows(JsonbException.class, () -> defaultJsonb.fromJson("{\"s1\":\"abc\"}", CreatorIncompatibleTypePojo.class));
assertTrue(e.getMessage().startsWith("Return type of creator"));
}

@Test
public void testMultipleCreatorsError() {
try {
defaultJsonb.fromJson("{\"s1\":\"abc\"}", CreatorMultipleDeclarationErrorPojo.class);
fail();
} catch (JsonbException e) {
assertTrue(e.getMessage().startsWith("More than one @JsonbCreator"));
}
JsonbException e = assertThrows(JsonbException.class, () -> defaultJsonb.fromJson("{\"s1\":\"abc\"}", CreatorMultipleDeclarationErrorPojo.class));
assertTrue(e.getMessage().startsWith("More than one @JsonbCreator"));
}

@Test
Original file line number Diff line number Diff line change
@@ -67,77 +67,53 @@ public void testTransientCollidesOnProperty() throws Exception {
JsonbTransientCollisionOnProperty pojo = new JsonbTransientCollisionOnProperty();
pojo.setTransientProperty("TRANSIENT");

try {
defaultJsonb.toJson(pojo);
fail();
} catch (JsonbException e) {
assertTrue(e.getMessage().startsWith("JsonbTransient annotation cannot be used with other jsonb annotations on the same property."));
}
JsonbException e = assertThrows(JsonbException.class, () -> defaultJsonb.toJson(pojo));
assertTrue(e.getMessage().startsWith("JsonbTransient annotation cannot be used with other jsonb annotations on the same property."));
}

@Test
public void testTransientCollidesOnGetter() throws Exception {
JsonbTransientCollisionOnGetter pojo = new JsonbTransientCollisionOnGetter();
pojo.setTransientProperty("TRANSIENT");

try {
defaultJsonb.toJson(pojo);
fail();
} catch (JsonbException e) {
assertTrue(e.getMessage().startsWith("JsonbTransient annotation cannot be used with other jsonb annotations on the same property."));
}
JsonbException e = assertThrows(JsonbException.class, () -> defaultJsonb.toJson(pojo));
assertTrue(e.getMessage().startsWith("JsonbTransient annotation cannot be used with other jsonb annotations on the same property."));
}

@Test
public void testTransientCollidesOnPropertyAndGetter() throws Exception {
JsonbTransientCollisionOnPropertyAndGetter pojo = new JsonbTransientCollisionOnPropertyAndGetter();
pojo.setTransientProperty("TRANSIENT");

try {
defaultJsonb.toJson(pojo);
fail();
} catch (JsonbException e) {
assertTrue(e.getMessage().startsWith("JsonbTransient annotation cannot be used with other jsonb annotations on the same property."));
}
JsonbException e = assertThrows(JsonbException.class, () -> defaultJsonb.toJson(pojo));
assertTrue(e.getMessage().startsWith("JsonbTransient annotation cannot be used with other jsonb annotations on the same property."));
}

@Test
public void testTransientCollidesOnSetter() throws Exception {
JsonbTransientCollisionOnSetter pojo = new JsonbTransientCollisionOnSetter();
pojo.setTransientProperty("TRANSIENT");

try {
defaultJsonb.toJson(pojo);
fail();
} catch (JsonbException e) {
assertTrue(e.getMessage().startsWith("JsonbTransient annotation cannot be used with other jsonb annotations on the same property."));
}
JsonbException e = assertThrows(JsonbException.class, () -> defaultJsonb.toJson(pojo));
assertTrue(e.getMessage().startsWith("JsonbTransient annotation cannot be used with other jsonb annotations on the same property."));
}

@Test
public void testTransientCollidesOnPropertyAndSetter() throws Exception {
JsonbTransientCollisionOnPropertyAndSetter pojo = new JsonbTransientCollisionOnPropertyAndSetter();
pojo.setTransientProperty("TRANSIENT");

try {
defaultJsonb.toJson(pojo);
fail();
} catch (JsonbException e) {
assertTrue(e.getMessage().startsWith("JsonbTransient annotation cannot be used with other jsonb annotations on the same property."));
}
JsonbException e = assertThrows(JsonbException.class, () -> defaultJsonb.toJson(pojo));
assertTrue(e.getMessage().startsWith("JsonbTransient annotation cannot be used with other jsonb annotations on the same property."));
}

@Test
public void testTransientCollidesOnPropertyAndGetterAndSetter() throws Exception {
JsonbTransientCollisionOnPropertyAndGetterAndSetter pojo = new JsonbTransientCollisionOnPropertyAndGetterAndSetter();
pojo.setTransientProperty("TRANSIENT");

try {
defaultJsonb.toJson(pojo);
fail();
} catch (JsonbException e) {
assertTrue(e.getMessage().startsWith("JsonbTransient annotation cannot be used with other jsonb annotations on the same property."));
}
JsonbException e = assertThrows(JsonbException.class, () -> defaultJsonb.toJson(pojo));
assertTrue(e.getMessage().startsWith("JsonbTransient annotation cannot be used with other jsonb annotations on the same property."));
}

@Test
Original file line number Diff line number Diff line change
@@ -25,6 +25,7 @@
import jakarta.json.JsonObject;
import jakarta.json.JsonObjectBuilder;
import jakarta.json.JsonWriter;
import jakarta.json.bind.JsonbException;
import jakarta.json.stream.JsonGenerator;

import java.io.StringWriter;
@@ -216,7 +217,7 @@ public static class NumberContainer {

@Test
public void testSerializeInvalidDouble() {
shouldFail(() -> defaultJsonb.toJson(Double.POSITIVE_INFINITY));
assertThrows(JsonbException.class, () -> defaultJsonb.toJson(Double.POSITIVE_INFINITY));

NumberContainer obj = new NumberContainer();
obj.doubleProp = Double.POSITIVE_INFINITY;
Original file line number Diff line number Diff line change
@@ -83,11 +83,7 @@ public void testSingleValue() {
assertEquals("5", bindingJsonb.toJson(5));

Jsonb jsonb = new JsonBindingBuilder().withConfig(new JsonbConfig().withStrictIJSON(true)).build();
try {
jsonb.toJson(5);
fail();
} catch (JsonbException exception){
assertEquals(Messages.getMessage(MessageKeys.IJSON_ENABLED_SINGLE_VALUE), exception.getMessage());
}
JsonbException exception = assertThrows(JsonbException.class, () -> jsonb.toJson(5));
assertEquals(Messages.getMessage(MessageKeys.IJSON_ENABLED_SINGLE_VALUE), exception.getMessage());
}
}
Original file line number Diff line number Diff line change
@@ -74,7 +74,7 @@
import static org.eclipse.yasson.Jsonbs.bindingJsonb;
import static org.eclipse.yasson.Jsonbs.defaultJsonb;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.fail;
import static org.junit.jupiter.api.Assertions.assertFalse;

/**
* This class contains tests for marshalling/unmarshalling dates.
@@ -194,9 +194,7 @@ private void testSqlDateWithTZ(TimeZone tz) {
@Test
public void testMarshallLocalDate() {
String jsonString = bindingJsonb.toJson(new LocalDateObj());
if (jsonString.contains("T")) {
fail("JSON contains time for a non Date that doesn't include time");
}
assertFalse(jsonString.contains("T"), "JSON contains time for a non Date that doesn't include time");
}

@Test
Original file line number Diff line number Diff line change
@@ -56,19 +56,11 @@ public void testMethodModifiers() {

@Test
public void testConstructorModifiers() {
try{
ProtectedConstructorClass instance = defaultJsonb.fromJson("{\"randomField\":\"test\"}", ProtectedConstructorClass.class);
assertEquals(instance.randomField, "test");
} catch (JsonbException e){
fail("No exception should be thrown for protected constructor");
throw e;
}
try {
defaultJsonb.fromJson("{\"randomField\":\"test\"}", PrivateConstructorClass.class);
fail("Exception should have been thrown");
}catch (JsonbException e){
assertTrue(e.getMessage().endsWith("Can't create instance"));
}
ProtectedConstructorClass instance = assertDoesNotThrow(() -> defaultJsonb.fromJson("{\"randomField\":\"test\"}", ProtectedConstructorClass.class), "No exception should be thrown for protected constructor");
assertEquals(instance.randomField, "test");

JsonbException e = assertThrows(JsonbException.class, () -> defaultJsonb.fromJson("{\"randomField\":\"test\"}", PrivateConstructorClass.class), "Exception should have been thrown");
assertTrue(e.getMessage().endsWith("Can't create instance"));
}

@Test
Original file line number Diff line number Diff line change
@@ -13,7 +13,7 @@
package org.eclipse.yasson.defaultmapping.specific;

import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.fail;
import static org.junit.jupiter.api.Assertions.assertThrows;

import java.util.Arrays;

@@ -44,44 +44,32 @@ public class RecursiveReferenceTest {
public void testSerializeRecursiveReference() {
Chain recursive = new Chain("test");
recursive.setLinksTo(recursive);
try {
Jsonbs.defaultJsonb.toJson(recursive);
fail("Exception should be caught");
} catch (JsonbException e) {
assertEquals(
"Unable to serialize property 'linksTo' from org.eclipse.yasson.adapters.model.Chain",
e.getMessage());
assertEquals(
"Recursive reference has been found in class class org.eclipse.yasson.adapters.model.Chain.",
e.getCause().getMessage());
}
JsonbException e = assertThrows(JsonbException.class, () -> Jsonbs.defaultJsonb.toJson(recursive), "Exception should be caught");
assertEquals(
"Unable to serialize property 'linksTo' from org.eclipse.yasson.adapters.model.Chain",
e.getMessage());
assertEquals(
"Recursive reference has been found in class class org.eclipse.yasson.adapters.model.Chain.",
e.getCause().getMessage());
}

@Test
public void testSerializeRecursiveReferenceCustomAdapter() {
Chain recursive = new Chain("test");
recursive.setLinksTo(recursive);
try {
adapterSerializerJsonb.toJson(recursive);
fail("Exception should be caught");
} catch (JsonbException e) {
assertEquals("Problem adapting object of type class org.eclipse.yasson.adapters.model.Chain to java.util.Map<java.lang"
+ ".String, java.lang.Object> in class class org.eclipse.yasson.adapters.model.ChainAdapter",
e.getMessage());
}
JsonbException e = assertThrows(JsonbException.class, () -> adapterSerializerJsonb.toJson(recursive), "Exception should be caught");
assertEquals("Problem adapting object of type class org.eclipse.yasson.adapters.model.Chain to java.util.Map<java.lang"
+ ".String, java.lang.Object> in class class org.eclipse.yasson.adapters.model.ChainAdapter",
e.getMessage());
}

@Test
public void testSerializeRecursiveReferenceCustomSerializer() {
Chain recursive = new Chain("test");
recursive.setLinksTo(recursive);
try {
userSerializerJsonb.toJson(recursive);
fail("Exception should be caught");
} catch (JsonbException e) {
assertEquals("Recursive reference has been found in class class org.eclipse.yasson.adapters.model.Chain.",
e.getMessage());
}
JsonbException e = assertThrows(JsonbException.class, () -> userSerializerJsonb.toJson(recursive), "Exception should be caught");
assertEquals("Recursive reference has been found in class class org.eclipse.yasson.adapters.model.Chain.",
e.getMessage());
}

@Test
Original file line number Diff line number Diff line change
@@ -43,7 +43,6 @@
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.junit.jupiter.api.Assertions.fail;

/**
* @author Roman Grigoriadi
@@ -68,13 +67,9 @@ public void setValue(String value) {
};
String expected = "{\"customInterface\":{\"value\":\"value1\"}}";
assertEquals(expected, defaultJsonb.toJson(unsupported));
try {
defaultJsonb.fromJson(expected, ClassWithUnsupportedFields.class);
fail("Should report an error");
} catch (JsonbException e) {
assertTrue(e.getMessage().contains("Cannot infer a type"));
assertTrue(e.getMessage().contains("customInterface"));
}
JsonbException e = assertThrows(JsonbException.class, () -> defaultJsonb.fromJson(expected, ClassWithUnsupportedFields.class), "Should report an error");
assertTrue(e.getMessage().contains("Cannot infer a type"));
assertTrue(e.getMessage().contains("customInterface"));
}

@Test
@@ -225,14 +220,9 @@ public void testEmptyStringAsOptionalLong() {
}

private void assertFail(String json, Type type, String failureProperty, Class<?> failurePropertyClass) {
try {
defaultJsonb.fromJson(json, type);
fail();
} catch (JsonbException e) {
if(!e.getMessage().contains(failureProperty) || !e.getMessage().contains(failurePropertyClass.getName())) {
fail("Expected error message to contain '" + failureProperty + "' and '" + failurePropertyClass.getName() + "', but was: " +
e.getMessage());
}
}
JsonbException e = assertThrows(JsonbException.class, () -> defaultJsonb.fromJson(json, type));
assertTrue(e.getMessage().contains(failureProperty) && e.getMessage().contains(failurePropertyClass.getName()), () ->
"Expected error message to contain '" + failureProperty + "' and '" + failurePropertyClass.getName() + "', but was: " +
e.getMessage());
}
}
Original file line number Diff line number Diff line change
@@ -15,7 +15,7 @@
import static org.eclipse.yasson.internal.AnnotationIntrospectorTestAsserts.assertCreatedInstanceContainsAllParameters;
import static org.eclipse.yasson.internal.AnnotationIntrospectorTestAsserts.assertParameters;
import static org.junit.jupiter.api.Assertions.assertNull;
import static org.junit.jupiter.api.Assertions.fail;
import static org.junit.jupiter.api.Assertions.assertThrows;

import jakarta.json.bind.JsonbConfig;
import jakarta.json.bind.config.PropertyNamingStrategy;
@@ -48,12 +48,8 @@ public class AnnotationIntrospectorWithoutOptionalModulesTest {
@Test
public void testNoConstructorPropertiesAnnotationWithoutOptionalModules() {
String className = "java.beans.ConstructorProperties";
try {
Class.forName(className);
fail("Class [" + className + "] should not be available for this test.");
} catch (ClassNotFoundException e) {
// OK, as expected
}
assertThrows(ClassNotFoundException.class, () -> Class.forName(className),
() -> "Class [" + className + "] should not be available for this test.");
}

@Test
Original file line number Diff line number Diff line change
@@ -16,15 +16,13 @@
import static org.junit.jupiter.api.Assertions.*;
import static org.eclipse.yasson.Jsonbs.*;

import org.eclipse.yasson.Assertions;
import org.eclipse.yasson.TestTypeToken;

import jakarta.json.bind.JsonbException;
import jakarta.json.stream.JsonGenerator;
import jakarta.json.stream.JsonParser;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.util.List;

public class PreinstantiatedJsonpTest {

@@ -138,12 +136,9 @@ public void testInvalidJsonParserAdvancedToCustomPosition() {
parser.next(); //START_OBJECT
//should be advanced further

try {
bindingYassonJsonb.fromJson(parser, Dog.class);
fail("JsonbException not thrown");
} catch (JsonbException e) {
//OK, parser in inconsistent state
}
//OK, parser in inconsistent state
assertThrows(JsonbException.class, () -> bindingYassonJsonb.fromJson(parser, Dog.class),
"JsonbException not thrown");
}

@Test
@@ -154,7 +149,7 @@ public void testInvalidGeneratorWrappedWithUserInteraction() {
generator.writeStartObject();
//key not written

Assertions.shouldFail(() -> bindingYassonJsonb.toJson(dog, generator));
assertThrows(JsonbException.class, () -> bindingYassonJsonb.toJson(dog, generator));
}

@Test
Original file line number Diff line number Diff line change
@@ -15,11 +15,12 @@
import jakarta.json.bind.Jsonb;
import jakarta.json.bind.JsonbBuilder;
import jakarta.json.bind.JsonbConfig;
import jakarta.json.bind.JsonbException;

import org.junit.jupiter.api.Test;

import static org.eclipse.yasson.Assertions.shouldFail;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;

import java.math.BigInteger;
@@ -224,6 +225,6 @@ public void testIncorrectTypeMapToObjectSerializer() {
Jsonb jsonb = JsonbBuilder.create();

String json = "{\"values\":{\"1\":\"OK\",\"error\":\"KO\"}}";
shouldFail(() -> jsonb.fromJson(json, MapObjectIntegerString.class));
assertThrows(JsonbException.class, () -> jsonb.fromJson(json, MapObjectIntegerString.class));
}
}
14 changes: 3 additions & 11 deletions src/test/java/org/eclipse/yasson/serializers/SerializersTest.java
Original file line number Diff line number Diff line change
@@ -79,8 +79,8 @@
import static org.eclipse.yasson.Jsonbs.nullableJsonb;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNull;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.junit.jupiter.api.Assertions.fail;
import static org.hamcrest.CoreMatchers.is;
import static org.hamcrest.MatcherAssert.assertThat;

@@ -368,17 +368,9 @@ public void testRecursiveSerializer() {

Box box = new Box();
box.boxStr = "Box to serialize";
try {
jsonb.toJson(box);
fail();
} catch (JsonbException ex) {
}
assertThrows(JsonbException.class, () -> jsonb.toJson(box));

try {
jsonb.fromJson("{\"boxStr\":\"Box to deserialize\"}", Box.class);
fail();
} catch (StackOverflowError error){
}
assertThrows(StackOverflowError.class, () -> jsonb.fromJson("{\"boxStr\":\"Box to deserialize\"}", Box.class));
}

@Test

0 comments on commit 3c65dbd

Please sign in to comment.