Start line:  
End line:  

Snippet Preview

Snippet HTML Code

Stack Overflow Questions
  /*
   * Copyright (C) 2005 The Guava 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 the License at
   *
   * http://www.apache.org/licenses/LICENSE-2.0
   *
  * Unless required by applicable law or agreed to in writing, software
  * distributed under the License is distributed on an "AS IS" BASIS,
  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  * See the License for the specific language governing permissions and
  * limitations under the License.
  */
 
 package com.google.common.testing;
 
 import static com.google.common.base.Preconditions.checkArgument;
 import static com.google.common.base.Preconditions.checkNotNull;
 
 
 
 import java.util.List;
 
 import  javax.annotation.Nullable;

A test utility that verifies that your methods and constructors throw NullPointerException or UnsupportedOperationException whenever null is passed to a parameter that isn't annotated with Nullable.

The tested methods and constructors are invoked -- each time with one parameter being null and the rest not null -- and the test fails if no expected exception is thrown. NullPointerTester uses best effort to pick non-null default values for many common JDK and Guava types, and also for interfaces and public classes that have public parameter-less constructors. When the non-null default value for a particular parameter type cannot be provided by NullPointerTester, the caller can provide a custom non-null default value for the parameter type via setDefault.

Author(s):
Kevin Bourrillion
Since:
10.0
 
 public final class NullPointerTester {
 
   private final ClassToInstanceMap<Objectdefaults =
       MutableClassToInstanceMap.create();
   private final List<MemberignoredMembers = Lists.newArrayList();
 
Sets a default value that can be used for any parameter of type type. Returns this object.
 
   public <T> NullPointerTester setDefault(Class<T> type, T value) {
     .putInstance(typecheckNotNull(value));
     return this;
   }

  
Ignore method in the tests that follow. Returns this object.

Since:
13.0
 
   public NullPointerTester ignore(Method method) {
     .add(checkNotNull(method));
     return this;
   }

  
Runs testConstructor on every constructor in class c that has at least minimalVisibility.
 
  public void testConstructors(Class<?> cVisibility minimalVisibility) {
    for (Constructor<?> constructor : c.getDeclaredConstructors()) {
      if (minimalVisibility.isVisible(constructor) && !isIgnored(constructor)) {
        testConstructor(constructor);
      }
    }
  }

  
Runs testConstructor on every public constructor in class c.
  public void testAllPublicConstructors(Class<?> c) {
  }

  
Runs testMethod on every static method of class c that has at least minimalVisibility, including those "inherited" from superclasses of the same package.
  public void testStaticMethods(Class<?> cVisibility minimalVisibility) {
    for (Method method : minimalVisibility.getStaticMethods(c)) {
      if (!isIgnored(method)) {
        testMethod(nullmethod);
      }
    }
  }

  
Runs testMethod on every public static method of class c, including those "inherited" from superclasses of the same package.
  public void testAllPublicStaticMethods(Class<?> c) {
  }

  
Runs testMethod on every instance method of the class of instance with at least minimalVisibility, including those inherited from superclasses of the same package.
  public void testInstanceMethods(Object instanceVisibility minimalVisibility) {
    for (Method method : getInstanceMethodsToTest(instance.getClass(), minimalVisibility)) {
      testMethod(instancemethod);
    }
  }
  ImmutableList<MethodgetInstanceMethodsToTest(Class<?> cVisibility minimalVisibility) {
    ImmutableList.Builder<Methodbuilder = ImmutableList.builder();
    for (Method method : minimalVisibility.getInstanceMethods(c)) {
      if (!isIgnored(method)) {
        builder.add(method);
      }
    }
    return builder.build();
  }

  
Runs testMethod on every public instance method of the class of instance, including those inherited from superclasses of the same package.
  public void testAllPublicInstanceMethods(Object instance) {
  }

  
Verifies that method produces a NullPointerException or UnsupportedOperationException whenever any of its non-Nullable parameters are null.

Parameters:
instance the instance to invoke method on, or null if method is static
  public void testMethod(@Nullable Object instanceMethod method) {
    Class<?>[] types = method.getParameterTypes();
    for (int nullIndex = 0; nullIndex < types.lengthnullIndex++) {
      testMethodParameter(instancemethodnullIndex);
    }
  }

  
Verifies that ctor produces a NullPointerException or UnsupportedOperationException whenever any of its non-Nullable parameters are null.
  public void testConstructor(Constructor<?> ctor) {
    Class<?> declaringClass = ctor.getDeclaringClass();
    checkArgument(Modifier.isStatic(declaringClass.getModifiers())
        || declaringClass.getEnclosingClass() == null,
        "Cannot test constructor of non-static inner class: %s"declaringClass.getName());
    Class<?>[] types = ctor.getParameterTypes();
    for (int nullIndex = 0; nullIndex < types.lengthnullIndex++) {
      testConstructorParameter(ctornullIndex);
    }
  }

  
Verifies that method produces a NullPointerException or UnsupportedOperationException when the parameter in position paramIndex is null. If this parameter is marked Nullable, this method does nothing.

Parameters:
instance the instance to invoke method on, or null if method is static
  public void testMethodParameter(
      @Nullable final Object instancefinal Method methodint paramIndex) {
    method.setAccessible(true);
    testParameter(instanceinvokable(instancemethod), paramIndexmethod.getDeclaringClass());
  }

  
Verifies that ctor produces a NullPointerException or UnsupportedOperationException when the parameter in position paramIndex is null. If this parameter is marked Nullable, this method does nothing.
  public void testConstructorParameter(Constructor<?> ctorint paramIndex) {
    ctor.setAccessible(true);
    testParameter(null, Invokable.from(ctor), paramIndexctor.getDeclaringClass());
  }

  
Visibility of any method or constructor.
  public enum Visibility {
    PACKAGE {
      @Override boolean isVisible(int modifiers) {
        return !Modifier.isPrivate(modifiers);
      }
    },
    PROTECTED {
      @Override boolean isVisible(int modifiers) {
        return Modifier.isPublic(modifiers) || Modifier.isProtected(modifiers);
      }
    },
    PUBLIC {
      @Override boolean isVisible(int modifiers) {
        return Modifier.isPublic(modifiers);
      }
    };
    abstract boolean isVisible(int modifiers);

    
Returns true if member is visible under this visibility.
    final boolean isVisible(Member member) {
      return isVisible(member.getModifiers());
    }
    final Iterable<MethodgetStaticMethods(Class<?> cls) {
      ImmutableList.Builder<Methodbuilder = ImmutableList.builder();
      for (Method method : getVisibleMethods(cls)) {
        if (Invokable.from(method).isStatic()) {
          builder.add(method);
        }
      }
      return builder.build();
    }
    final Iterable<MethodgetInstanceMethods(Class<?> cls) {
      ConcurrentMap<SignatureMethodmap = Maps.newConcurrentMap();
      for (Method method : getVisibleMethods(cls)) {
        if (!Invokable.from(method).isStatic()) {
          map.putIfAbsent(new Signature(method), method);
        }
      }
      return map.values();
    }
    private ImmutableList<MethodgetVisibleMethods(Class<?> cls) {
      // Don't use cls.getPackage() because it does nasty things like reading
      // a file.
      String visiblePackage = Reflection.getPackageName(cls);
      ImmutableList.Builder<Methodbuilder = ImmutableList.builder();
      for (Class<?> type : TypeToken.of(cls).getTypes().classes().rawTypes()) {
        if (!Reflection.getPackageName(type).equals(visiblePackage)) {
          break;
        }
        for (Method method : type.getDeclaredMethods()) {
          if (!method.isSynthetic() && isVisible(method)) {
            builder.add(method);
          }
        }
      }
      return builder.build();
    }
  }
  // TODO(benyu): Use labs/reflect/Signature if it graduates.
  private static final class Signature {
    private final String name;
    private final ImmutableList<Class<?>> parameterTypes;
    Signature(Method method) {
      this(method.getName(), ImmutableList.copyOf(method.getParameterTypes()));
    }
    Signature(String nameImmutableList<Class<?>> parameterTypes) {
      this. = name;
      this. = parameterTypes;
    }
    @Override public boolean equals(Object obj) {
      if (obj instanceof Signature) {
        Signature that = (Signatureobj;
        return .equals(that.name)
            && .equals(that.parameterTypes);
      }
      return false;
    }
    @Override public int hashCode() {
      return Objects.hashCode();
    }
  }

  
Verifies that invokable produces a NullPointerException or UnsupportedOperationException when the parameter in position paramIndex is null. If this parameter is marked Nullable, this method does nothing.

Parameters:
instance the instance to invoke invokable on, or null if invokable is static
  private void testParameter(Object instanceInvokable<?, ?> invokable,
      int paramIndexClass<?> testedClass) {
    if (isPrimitiveOrNullable(invokable.getParameters().get(paramIndex))) {
      return// there's nothing to test
    }
    Object[] params = buildParamList(invokableparamIndex);
    try {
      @SuppressWarnings("unchecked"// We'll get a runtime exception if the type is wrong.
      Invokable<Object, ?> unsafe = (Invokable<Object, ?>) invokable;
      unsafe.invoke(instanceparams);
      Assert.fail("No exception thrown for parameter at index " + paramIndex
          + " from " + invokable + Arrays.toString(params) + " for " + testedClass);
    } catch (InvocationTargetException e) {
      Throwable cause = e.getCause();
      if (.isExpectedType(cause)) {
        return;
      }
      AssertionFailedError error = new AssertionFailedError(
          "wrong exception thrown from " + invokable + ": " + cause);
      error.initCause(cause);
      throw error;
    } catch (IllegalAccessException e) {
      throw new RuntimeException(e);
    }
  }
  private Object[] buildParamList(Invokable<?, ?> invokableint indexOfParamToSetToNull) {
    ImmutableList<Parameterparams = invokable.getParameters();
    Object[] args = new Object[params.size()];
    for (int i = 0; i < args.lengthi++) {
      Parameter param = params.get(i);
      if (i != indexOfParamToSetToNull) {
        args[i] = getDefaultValue(param.getType());
        Assert.assertTrue(
            "Can't find or create a sample instance for type '"
                + param.getType()
                + "'; please provide one using NullPointerTester.setDefault()",
            args[i] != null || isNullable(param));
      }
    }
    return args;
  }
  private <T> T getDefaultValue(TypeToken<T> type) {
    // We assume that all defaults are generics-safe, even if they aren't,
    // we take the risk.
    @SuppressWarnings("unchecked")
    T defaultValue = (T) .getInstance(type.getRawType());
    if (defaultValue != null) {
      return defaultValue;
    }
    @SuppressWarnings("unchecked"// All arbitrary instances are generics-safe
    T arbitrary = (T) ArbitraryInstances.get(type.getRawType());
    if (arbitrary != null) {
      return arbitrary;
    }
    if (type.getRawType() == Class.class) {
      // If parameter is Class<? extends Foo>, we return Foo.class
      @SuppressWarnings("unchecked")
      T defaultClass = (T) getFirstTypeParameter(type.getType()).getRawType();
      return defaultClass;
    }
    if (type.getRawType() == TypeToken.class) {
      // If parameter is TypeToken<? extends Foo>, we return TypeToken<Foo>.
      @SuppressWarnings("unchecked")
      T defaultType = (T) getFirstTypeParameter(type.getType());
      return defaultType;
    }
    if (type.getRawType() == Converter.class) {
      TypeToken<?> convertFromType = type.resolveType(
          Converter.class.getTypeParameters()[0]);
      TypeToken<?> convertToType = type.resolveType(
          Converter.class.getTypeParameters()[1]);
      @SuppressWarnings("unchecked"// returns default for both F and T
      T defaultConverter = (T) defaultConverter(convertFromTypeconvertToType);
      return defaultConverter;
    }
    if (type.getRawType().isInterface()) {
      return newDefaultReturningProxy(type);
    }
    return null;
  }
  private <F, T> Converter<F, T> defaultConverter(
      final TypeToken<F> convertFromTypefinal TypeToken<T> convertToType) {
    return new Converter<F, T>() {
      @Override protected T doForward(F a) {
        return doConvert(convertToType);
      }
      @Override protected F doBackward(T b) {
        return doConvert(convertFromType);
      }
      private /*static*/ <S> S doConvert(TypeToken<S> type) {
        return checkNotNull(getDefaultValue(type));
      }
    };
  }
  private static TypeToken<?> getFirstTypeParameter(Type type) {
    if (type instanceof ParameterizedType) {
      return TypeToken.of(
          ((ParameterizedTypetype).getActualTypeArguments()[0]);
    } else {
      return TypeToken.of(Object.class);
    }
  }
  private <T> T newDefaultReturningProxy(final TypeToken<T> type) {
    return new DummyProxy() {
      @Override <R> R dummyReturnValue(TypeToken<R> returnType) {
        return getDefaultValue(returnType);
      }
    }.newProxy(type);
  }
  private static Invokable<?, ?> invokable(@Nullable Object instanceMethod method) {
    if (instance == null) {
      return Invokable.from(method);
    } else {
      return TypeToken.of(instance.getClass()).method(method);
    }
  }
  static boolean isPrimitiveOrNullable(Parameter param) {
    return param.getType().getRawType().isPrimitive() || isNullable(param);
  }
  private static boolean isNullable(Parameter param) {
    return param.isAnnotationPresent(Nullable.class);
  }
  private boolean isIgnored(Member member) {
    return member.isSynthetic() || .contains(member);
  }

  
Strategy for exception type matching used by NullPointerTester.
  private enum ExceptionTypePolicy {

    
Exceptions should be NullPointerException or UnsupportedOperationException.
    NPE_OR_UOE() {
      @Override
      public boolean isExpectedType(Throwable cause) {
        return cause instanceof NullPointerException
            || cause instanceof UnsupportedOperationException;
      }
    },

    
Exceptions should be NullPointerException, IllegalArgumentException, or UnsupportedOperationException.
    NPE_IAE_OR_UOE() {
      @Override
      public boolean isExpectedType(Throwable cause) {
        return cause instanceof NullPointerException
            || cause instanceof IllegalArgumentException
            || cause instanceof UnsupportedOperationException;
      }
    };
    public abstract boolean isExpectedType(Throwable cause);
  }
New to GrepCode? Check out our FAQ X