0

I am using the library lift json in scala to deserialize some json configurations to my Config Case class. For deserializing I have a class called Parser. It has a get method which tries to deserialize the config and if successful then returns scala.util.Success(Config) otherwise scala.util.Failure. My question is what is the correct way to write unit test for Parser class ?

  1. Should I just keep various valid and invalid configuration jsons in test data and just assert isFailure and isSuccess from the result of the get method ?
  2. Or for each test json configuration I have, I create an exact Config class by hand, and then assert isFailure,isSuccess and if isSuccess also assert that deserialized config and the one I created by hand are the same ?
advocateofnone
  • 2,527
  • 3
  • 17
  • 39

1 Answers1

2

The first approach is obviously insufficient: it could pass all tests while giving wrong fields for the Config.

So you need the second, but of course the Config only exists for the valid configurations, and it would be simpler to use isEqual(Success(expectedConfig)) instead of isSuccess and isEqual separately (maybe extract it to a method). Or if you use ScalaTest, consider TryValues.

This is also a very good use-case for property testing (ScalaCheck is the most common Scala library): if you have also serialization methods, generate arbitrary configs and test that

fromJson(config.toJson) == Success(config)
Alexey Romanov
  • 167,066
  • 35
  • 309
  • 487