Method for unit-testing commitChanges() in cayenne-based applications

From: Mike Kienenberger (mkienen..laska.net)
Date: Wed Aug 25 2004 - 17:42:45 EDT

  • Next message: Andrus Adamchik: "Re: Method for unit-testing commitChanges() in cayenne-based applications"

    For anyone looking to perform unit testing on a cayenne-based application,
    here's one strategy you can use to simulate a database [cayenne] failure.
    It does require that your application grabs the DataContext from some kind
    of factory method (such as BasicServletConfiguration.getDefaultContext() for
    web applications or perhaps is passed into your class for a standalone
    application).

    Just call "setThrowExceptionOnCommitChanges(true);" using the code below to
    force your tests to fail.

    Unfortunately, I couldn't figure out any way to set up such an intercept if
    an application directly calls DataContext.createDataContext(), but that's
    not applicable in my current situation.

    Perhaps some future version of Cayenne should provide a way to specify a
    DataContextFactory.

    I'd be curious to hear how others are doing unit tests on commitChanges().
    Maybe I'm missing something more obvious. My original idea was to handle
    this at the JDBC level, but that seemed like overkill (although potentially
    more realistic).

    -Mike

    -----------------------------------------------------------------------------
    ----------------------------

            private DataContext defaultDataContext = null;

        public DataContext getDataContext()
        {
            if (null == defaultDataContext)
            {
                            defaultDataContext =
    BasicServletConfiguration.getDefaultContext(aRequest.getSession());

                
                EventManager mgr = EventManager.getDefaultManager();
                mgr.addListener(
                    this,
                    "dataContextWillCommit",
                    DataContextEvent.class,
                    DataContext.WILL_COMMIT,
                    defaultDataContext);
                
                DataContext.setTransactionEventsEnabledDefault(true);
            }
            
            return defaultDataContext;
        }

        private boolean shouldThrowExceptionOnCommitChanges = false;
        
        public void setThrowExceptionOnCommitChanges(boolean
    shouldThrowExceptionOnCommitChanges)
        {
            this.shouldThrowExceptionOnCommitChanges =
    shouldThrowExceptionOnCommitChanges;
        }
        
        public void dataContextWillCommit(DataContextEvent event)
        {
            if (shouldThrowExceptionOnCommitChanges)
                throw new CayenneRuntimeException("Forced Testing Failure");
        }



    This archive was generated by hypermail 2.0.0 : Wed Aug 25 2004 - 17:41:55 EDT