mercredi 2 septembre 2015

Constructor and Unit Testing

I have a class XmlRecord. This class will deal with reading/writing to an xml file. At the moment, I have the following for that class:

class XmlRecord {
   private val _file = new File("file.xml")
}

I want this class to somehow create the file if it doesn't exist. I know how to achieve this but I'm unsure how to design it in an Object Orientated way. I think I have two options:

  1. Do I add a code to the constructor (or a call to a private method) that will create this file automatically if it doesn't exist. My problem with this method is that how do I unit test this as this code is effectively private code? Would I have to inject the File dependency so it could be mocked during testing?

  2. Do I get the constructor to return an exception or implement a public method for the class so that the caller can use it to check if a file needs to be created? If so, the caller would then call another public method that would create the file. Again I think I would need to inject the dependency.

I hope that makes sense. I'm just trying to get a better grasp on designing my classes.

Aucun commentaire:

Enregistrer un commentaire