How to unit test Property Value Converters
# help-with-umbraco
a
Are there any guides on how to unit test a property value converter?
d
No guides as far as I'm aware, anything you're struggling with in particular?
a
I think I've got it, just running some final tests and I'll share my code. Just need to test that the json string gets deserialized correctly
Copy code
[Fact]
        public void JsonValueConverterTests()
        {
            //Arrange
            var metaData = new Dictionary<string, string>
            {
                { "Dictionary Key 1", "Dictionary Value 1" },
                { "Dictionary Key 2", "Dictionary Value 2" }
            };

            var jsonString = @"[
  {
    ""value"": ""Dictionary Value 1"",
    ""hasFocus"": true,
    ""name"": ""Dictionary Key 1""
  },
  {
    ""value"": ""Dictionary Value 2"",
    ""hasFocus"": true,
    ""name"": ""Dictionary Key 2""
  }
]";

            //Act
            var converter = new MetaDataValueConverter(new JsonNetSerializer());
            var result = converter.ConvertSourceToIntermediate(null, null, jsonString, false);

            // Assert
            Assert.Equal(metaData, result);
        }

        [Fact]
        public void TypeValueConverterTests()
        {
            //Arrange
            var metaData = new List<UmbCheckoutMetaData>
            {
                new()
                {
                    Name = "Dictionary Key 1",
                    Value = "Dictionary Value 1"
                },
                new()
                {
                    Name = "Dictionary Key 2",
                    Value = "Dictionary Value 2"
                }
            };

            var metaDataDictionary = new Dictionary<string, string>
            {
                { "Dictionary Key 1", "Dictionary Value 1" },
                { "Dictionary Key 2", "Dictionary Value 2" }
            };

            var jsonSerializer = new JsonNetSerializer();
            var jsonString = jsonSerializer.Serialize(metaData);

            //Act
            var converter = new MetaDataValueConverter(new JsonNetSerializer());
            var result = converter.ConvertSourceToIntermediate(null, null, jsonString, false);

            // Assert
            Assert.Equal(metaDataDictionary, result);
        }
They seem to work and pass
d
Nice! From your description, it sounds more as if you're testing the jsonserializer rather than the actual value converter
2 Views