我正在实现一个可序列化的类(因此它是一个使用w / RMI的值对象)。但我需要测试它。有没有办法轻松做到这一点?
澄清:我正在实现这个类,所以在类定义中坚持使用Serializable是微不足道的。我需要手动序列化/反序列化它以查看它是否有效。
我发现这个C# question,Java有类似的答案吗?
答案 0 :(得分:114)
简单的方法是检查对象是java.io.Serializable
还是java.io.Externalizable
的实例,但这并不能真正证明对象确实是可序列化的。
唯一可靠的方法是尝试真实。最简单的测试类似于:
new ObjectOutputStream(new ByteArrayOutputStream()).writeObject(myObject);
并检查它不会抛出异常。
Apache Commons Lang提供了一个更简短的版本:
SerializationUtils.serialize(myObject);
再次检查异常。
你可以更加严谨,并检查它是否反序列化为与原始版本相同的东西:
Serializable original = ...
Serializable copy = SerializationUtils.clone(original);
assertEquals(original, copy);
等等。
答案 1 :(得分:22)
基于skaffman答案的实用方法:
private static <T extends Serializable> byte[] pickle(T obj)
throws IOException
{
ByteArrayOutputStream baos = new ByteArrayOutputStream();
ObjectOutputStream oos = new ObjectOutputStream(baos);
oos.writeObject(obj);
oos.close();
return baos.toByteArray();
}
private static <T extends Serializable> T unpickle(byte[] b, Class<T> cl)
throws IOException, ClassNotFoundException
{
ByteArrayInputStream bais = new ByteArrayInputStream(b);
ObjectInputStream ois = new ObjectInputStream(bais);
Object o = ois.readObject();
return cl.cast(o);
}
答案 2 :(得分:3)
简短的回答是,您可以提出一些候选对象,并尝试使用您选择的机制对它们进行序列化。这里的测试是在编组/解组时没有遇到错误,并且得到的“再水化”对象与原始对象相同。
或者,如果您没有任何候选对象,则可以实现基于反射的测试,该测试会对您的类的(非静态,非瞬态)字段进行内省,以确保它们也是Serializable。从经验来看,这令人惊讶地迅速变得复杂,但它可以在合理的范围内完成。
后一种方法的缺点是如果一个场是例如List<String>
,那么你可以在没有严格可序列化字段的情况下使类失败,或者只是假设将使用List的可序列化实现。两者都不完美。 (请注意,后一个问题也存在于示例中;如果测试中使用的每个示例都使用可序列化的列表,那么在实践中没有什么可以防止其他代码使用非序列化版本。)
答案 3 :(得分:3)
这段代码应该这样做......
import java.io.ByteArrayOutputStream;
import java.io.Externalizable;
import java.io.IOException;
import java.io.ObjectOutputStream;
import java.io.OutputStream;
import java.io.Serializable;
public class Main
{
public static void main(String[] args)
{
System.out.println(isSerializable("Hello"));
System.out.println(isSerializable(new Main()));
}
public static boolean isSerializable(final Object o)
{
final boolean retVal;
if(implementsInterface(o))
{
retVal = attemptToSerialize(o);
}
else
{
retVal = false;
}
return (retVal);
}
private static boolean implementsInterface(final Object o)
{
final boolean retVal;
retVal = ((o instanceof Serializable) || (o instanceof Externalizable));
return (retVal);
}
private static boolean attemptToSerialize(final Object o)
{
final OutputStream sink;
ObjectOutputStream stream;
stream = null;
try
{
sink = new ByteArrayOutputStream();
stream = new ObjectOutputStream(sink);
stream.writeObject(o);
// could also re-serilalize at this point too
}
catch(final IOException ex)
{
return (false);
}
finally
{
if(stream != null)
{
try
{
stream.close();
}
catch(final IOException ex)
{
// should not be able to happen
}
}
}
return (true);
}
}
答案 4 :(得分:2)
您可以进行以下测试:
以下是将对象序列化和反序列化为文件的示例:
答案 5 :(得分:2)
这仅适用于完全填充的对象,如果您要求顶级对象中包含的任何对象也可序列化,则它们不能为null,因为序列化/反序列化会跳过空对象,因此该测试无效
答案 6 :(得分:0)
我尝试编写一个单元测试(使用Spock在Groovy中),它可以检查供RMI使用的给定接口实际上是完全可序列化的-所有参数,异常以及方法中定义的类型的可能实现
到目前为止,这似乎对我来说仍然有效,但是,这样做有点奇怪,并且在某些情况下可能无法解决,因此后果自负!
您将需要用自己的示例接口Notification
等替换。该示例包括一个不可序列化的字段作为说明。
package example
import groovy.transform.CompileDynamic
import groovy.transform.CompileStatic
import spock.lang.Specification
import java.lang.reflect.*
import java.rmi.Remote
import java.rmi.RemoteException
/** This checks that the a remoting API NotifierServer is safe
*
* It attempts to flush out any parameter classes which are
* not Serializable. This isn't checked at compile time!
*
*/
@CompileStatic
class RemotableInterfaceTest extends Specification {
static class NotificationException extends RuntimeException {
Object unserializable
}
static interface Notification {
String getMessage()
Date getDate()
}
static interface Notifier extends Remote {
void accept(Notification notification) throws RemoteException, NotificationException
}
static interface NotifierServer extends Remote {
void subscribe(Notification notifier) throws RemoteException
void notify(Notification message) throws RemoteException
}
// From https://www.javaworld.com/article/2077477/learn-java/java-tip-113--identify-subclasses-at-runtime.html
/**
* Scans all classes accessible from the context class loader which belong to the given package and subpackages.
*
* @param packageName The base package
* @return The classes
* @throws ClassNotFoundException
* @throws IOException
*/
static Class[] getClasses(String packageName)
throws ClassNotFoundException, IOException {
ClassLoader classLoader = Thread.currentThread().getContextClassLoader()
assert classLoader != null
String path = packageName.replace('.', '/')
Enumeration resources = classLoader.getResources(path)
List<File> dirs = new ArrayList()
while (resources.hasMoreElements()) {
URL resource = resources.nextElement()
dirs.add(new File(resource.getFile()))
}
ArrayList classes = new ArrayList()
for (File directory : dirs) {
classes.addAll(findClasses(directory, packageName))
}
return classes.toArray(new Class[classes.size()])
}
/**
* Recursive method used to find all classes in a given directory and subdirs.
*
* @param directory The base directory
* @param packageName The package name for classes found inside the base directory
* @return The classes
* @throws ClassNotFoundException
*/
static List<Class> findClasses(File directory, String packageName) throws ClassNotFoundException {
List<Class> classes = new ArrayList()
if (!directory.exists()) {
return classes
}
File[] files = directory.listFiles()
for (File file : files) {
if (file.isDirectory()) {
//assert !file.getName().contains(".");
classes.addAll(findClasses(file, packageName + "." + file.getName()))
} else if (file.getName().endsWith(".class")) {
classes.add(Class.forName(packageName + '.' + file.getName().substring(0, file.getName().length() - 6)))
}
}
return classes
}
/** Finds all known subclasses of a class */
@CompileDynamic
static List<Class> getSubclasses(Class type) {
allClasses
.findAll { Class it ->
!Modifier.isAbstract(it.modifiers) &&
it != type &&
type.isAssignableFrom(it)
}
}
/** Checks if a type is nominally serializable or remotable.
*
* Notes:
* <ul>
* <li> primitives are implicitly serializable
* <li> interfaces are serializable or remotable by themselves, but we
* assume that since #getSerializedTypes checks derived types of interfaces,
* we can safely assume that all implementations will be checked
*</ul>
*
* @param it
* @return
*/
static boolean isSerializableOrRemotable(Class<?> it) {
return it.primitive || it.interface || Serializable.isAssignableFrom(it) || Remote.isAssignableFrom(it)
}
/** Recursively finds all (new) types associated with a given type
* which need to be serialized because they are fields, parameterized
* types, implementations, etc. */
static void getSerializedTypes(final Set<Class<?>> types, Type... it) {
for(Type type in it) {
println "type: $type.typeName"
if (type instanceof GenericArrayType) {
type = ((GenericArrayType)type).genericComponentType
}
if (type instanceof ParameterizedType) {
ParameterizedType ptype = (ParameterizedType)type
getSerializedTypes(types, ptype.actualTypeArguments)
break
}
if (type instanceof Class) {
Class ctype = (Class)type
if (ctype == Object)
break
if (types.contains(type))
break
types << ctype
for (Field field : ctype.declaredFields) {
println "${ctype.simpleName}.${field.name}: ${field.type.simpleName}"
if (Modifier.isVolatile(field.modifiers) ||
Modifier.isTransient(field.modifiers) ||
Modifier.isStatic(field.modifiers))
continue
Class<?> fieldType = field.type
if (fieldType.array)
fieldType = fieldType.componentType
if (types.contains(fieldType))
continue
types << fieldType
if (!fieldType.primitive)
getSerializedTypes(types, fieldType)
}
if (ctype.genericSuperclass) {
getSerializedTypes(types, ctype.genericSuperclass)
}
getSubclasses(ctype).each { Class c -> getSerializedTypes(types, c) }
break
}
}
}
/** Recursively checks a type's methods for related classes which
* need to be serializable if the type is remoted */
static Set<Class<?>> getMethodTypes(Class<?> it) {
Set<Class<?>> types = []
for(Method method: it.methods) {
println "method: ${it.simpleName}.$method.name"
getSerializedTypes(types, method.genericParameterTypes)
getSerializedTypes(types, method.genericReturnType)
getSerializedTypes(types, method.genericExceptionTypes)
}
return types
}
/** All the known defined classes */
static List<Class> allClasses = Package.packages.collectMany { Package p -> getClasses(p.name) as Collection<Class> }
@CompileDynamic
def "NotifierServer interface should only expose serializable or remotable types"() {
given:
Set<Class> types = getMethodTypes(NotifierServer)
Set<Class> nonSerializableTypes = types.findAll { !isSerializableOrRemotable(it) }
expect:
nonSerializableTypes.empty
}
}