Fix Assert.instanceOf exception message

Update the exception message used when Assert.instanceOf fails such
that it expects the provided message to end with '.'. This reverts
commit 5874383ef0 which caused the
implementation to be at odds with the JavaDoc and the previous
release.

The updated code also has the benefit of protecting against a null
message.

Issue: SPR-10269
master
Phillip Webb 12 years ago
parent 2aaa66f86b
commit 7bbb4ec7af
  1. 7
      spring-core/src/main/java/org/springframework/util/Assert.java
  2. 23
      spring-core/src/test/java/org/springframework/util/AssertTests.java

@ -1,5 +1,5 @@
/*
* Copyright 2002-2012 the original author or authors.
* Copyright 2002-2013 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
@ -334,8 +334,9 @@ public abstract class Assert {
public static void isInstanceOf(Class type, Object obj, String message) {
notNull(type, "Type to check against must not be null");
if (!type.isInstance(obj)) {
throw new IllegalArgumentException(message +
". Object of class [" + (obj != null ? obj.getClass().getName() : "null") +
throw new IllegalArgumentException(
(StringUtils.hasLength(message) ? message + " " : "") +
"Object of class [" + (obj != null ? obj.getClass().getName() : "null") +
"] must be an instance of " + type);
}
}

@ -1,5 +1,5 @@
/*
* Copyright 2002-2012 the original author or authors.
* Copyright 2002-2013 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@ -24,7 +24,9 @@ import java.util.List;
import java.util.Map;
import java.util.Set;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ExpectedException;
/**
* Unit tests for the {@link Assert} class.
@ -36,6 +38,9 @@ import org.junit.Test;
*/
public class AssertTests {
@Rule
public ExpectedException thrown = ExpectedException.none();
@Test(expected = IllegalArgumentException.class)
public void instanceOf() {
final Set<?> set = new HashSet<Object>();
@ -43,6 +48,22 @@ public class AssertTests {
Assert.isInstanceOf(HashMap.class, set);
}
@Test
public void instanceOfNoMessage() throws Exception {
thrown.expect(IllegalArgumentException.class);
thrown.expectMessage("Object of class [java.lang.Object] must be an instance " +
"of interface java.util.Set");
Assert.isInstanceOf(Set.class, new Object(), null);
}
@Test
public void instanceOfMessage() throws Exception {
thrown.expect(IllegalArgumentException.class);
thrown.expectMessage("Custom message. Object of class [java.lang.Object] must " +
"be an instance of interface java.util.Set");
Assert.isInstanceOf(Set.class, new Object(), "Custom message.");
}
@Test
public void isNullDoesNotThrowExceptionIfArgumentIsNullWithMessage() {
Assert.isNull(null, "Bla");

Loading…
Cancel
Save