Exemple #1
0
        public void Can_Convert_POCO_collections_with_custom_Converter()
        {
            AutoMapping.RegisterConverter((User from) => {
                var to        = from.ConvertTo <UserDto>(skipConverters: true); // avoid infinite recursion
                to.FirstName += "!";
                to.LastName  += "!";
                return(to);
            });
            AutoMapping.RegisterConverter((Car from) => $"{from.Name} ({from.Age})");

            var user = new User {
                FirstName = "John",
                LastName  = "Doe",
                Car       = new Car {
                    Name = "BMW X6", Age = 3
                }
            };
            var users = new UsersData {
                Id        = 1,
                User      = user,
                UsersList = { user },
                UsersMap  = { { 1, user } }
            };

            var dtoUsers = users.ConvertTo <UsersDto>();

            Assert.That(dtoUsers.Id, Is.EqualTo(users.Id));

            void AssertUser(UserDto userDto)
            {
                Assert.That(userDto.FirstName, Is.EqualTo(user.FirstName + "!"));
                Assert.That(userDto.LastName, Is.EqualTo(user.LastName + "!"));
                Assert.That(userDto.Car, Is.EqualTo($"{user.Car.Name} ({user.Car.Age})"));
            }

            AssertUser(user.ConvertTo <UserDto>());
            AssertUser(dtoUsers.User);
            AssertUser(dtoUsers.UsersList[0]);
            AssertUser(dtoUsers.UsersMap[1]);

            AutoMappingUtils.Reset();
        }