scalamockingcake-pattern

Junits using Mocks scala traits and cake pattern


I have a scala trait as follows -

trait Mytrait {
   def saveData : Boolean = {
      //make database calls to store
      true
   }
    def getData : Integer = {
        //get data from database
        return i
    }

}

Now I have heard about cake pattern but I am not able to figure out how I can apply cake pattern for mocking traits like this.

Can anyone point out on how this can be done?


Solution

  • You would do it something like this:

    trait Mytrait { this: DbConnectionFactory => // Require this trait to be mixed with a DbConnectionFactory
      def saveData : Boolean = {
        val connection = getConnection // Supplied by DbConnectionFactory 'layer'
        //use DB connection to make database calls to store
        true
      }
    
      def getData : Integer = {
        val connection = getConnection // Supplied by DbConnectionFactory 'layer'
        val i: Integer = ... // use DB connection to get data from database
        return i
      }
    
    }
    
    trait DbConnection
    
    trait DbConnectionFactory {
      def getConnection: DbConnection
    }
    
    // --- for prod:
    
    class ProdDbConnection extends DbConnectionFactory {
      // Set up conn to prod Db - say, an Oracle DB instance
      def getConnection: DbConnection = ???
    } // or interpose a connection pooling implementation over a set of these, or whatever
    
    val myProdDbWorker = new ProdDbConnection with Mytrait
    
    // --- for test:
    
    class MockDbConnection extends DbConnectionFactory {
      // Set up mock conn
      def getConnection: DbConnection = ???
    }
    
    val myTestDbWorker = new MockDbConnection with Mytrait
    

    where you form the 'layers' or your 'cake' from a suitable DbConnectionFactory and your trait.

    This is just a simple example, you could expand on the number of components involved, have multiple implementations of MyTrait that you want to work with under different cirumstances, etc. See, for example Dependency Injection in Scala: Extending the Cake Pattern