Skip to content

Bi-directional mapping of Object/String fields with empty string fails (unit test) #334

Description

@skjardenCode

Hello,

I came across a trivial use case, where I had to map between two simple classes, where one property is of type Object and the other is a String. When I map from class A to class B and immediately back from (mapped) B to A while using an empty string for the mapped property, Dozer "loses" the empty string and sets the property to null.

(Edit: I'm using Dozer 5.5.1.)

Please see this small unit test, that fails at the last assertEquals:

import static org.junit.Assert.assertEquals;

import org.apache.log4j.Level;
import org.apache.log4j.Logger;
import org.dozer.DozerBeanMapper;
import org.junit.Before;
import org.junit.Test;

public class DozerEmptyStringMappingTest
{
    @Test
    public void test_mapEmptyString()
    {
        DozerBeanMapper dozerBeanMapper = new DozerBeanMapper();

        
        // Test bi-directional mapping with non-empty string

        ClassA classA = new ClassA();
        classA.setName( "Not Empty" );
        
        ClassB classB = dozerBeanMapper.map( classA, ClassB.class );
        ClassA mappedClassA = dozerBeanMapper.map( classB, ClassA.class );

        assertEquals( "Not Empty", classB.getName() );
        assertEquals( "Not Empty", mappedClassA.getName() );
    
    
        // Test bi-directional mapping with empty string
        
        classA.setName( "" );
    
        classB = dozerBeanMapper.map( classA, ClassB.class );
        mappedClassA = dozerBeanMapper.map( classB, ClassA.class );

        assertEquals( "", classB.getName() );
        assertEquals( "", mappedClassA.getName() );      // Fails: 'getName()' returns null 
    }

    public static class ClassA
    {
        private Object name;

        public Object getName()
        {
            return name;
        }

        public void setName( Object name )
        {
            this.name = name;
        }
    }

    public static class ClassB
    {
        private String  name;

        public String getName()
        {
            return name;
        }

        public void setName( String name )
        {
            this.name = name;
        }
    }
}

Since there is a mapping between Object and String, I would have guessed Dozer might not to be able to map the string without a type hint. But, because the mapping behaves correctly with a non-empty string, I think the failure of the last assert may be a bug in Dozer or at least a weird default-behavior.

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions