fuzzelogic Solutions

February 8, 2010

Auto mocking coolness

Filed under: BDD, OO, Programming, c#, design — Tags: , , , — admin @ 5:57 pm

Hi! All

Say a big thank you to the structure map guys :- the dependency injection framework with a bit more. It now has Auto mocking. This is great for removing the chattiness of creating mocks for your test classes, and becuase it can use the Rhino AAA style you can don’t have to explicitly define your expectations. :-)

Assume you have a the following class

public class LicenseCatalog {
// this has a dependency on an ILicenseRepository implementation
    public LicenseCatalog (ILicenseRepository repository, ILicenseUpdater updater) {
//….
}
}

Here’s a test using it..

public abstract class get_the_licenseFeature: is_a_feature_provided_by<ILicenseCatalog>{
        [Scenario][Category("in_a_scenario_where<we_get_the_license_file>")]
        public class if_the_settings_file_has_all_the_settings: in_a_scenario_where<we_get_the_license_file>{

            [Observation]
            public void it_should_tell_the_repository_to_load_the_license_file_and_update_the_license(){
                If(x => x.settings_file = new Settings(){hidden_file_name = "hidden", license_file_name = "license"})
                    .when_you_tell(x => x.the_system_under_test.get_license())
                    .observer_that(x => x.repository.was_told_to(r => r.get_license()))
                    .And (x=>x.updater.was_told_to(u=>u.update_license_file());
            }
        }

        public class we_get_the_license_file : baseContext {
            public Settings settings_file;
        }

        public class baseContext : get_the_licenseFeature{
            <strong>RhinoAutoMocker<LicenseCatalog> mocker = new RhinoAutoMocker<LicenseCatalog>();</strong>
            public ILicenseRepository repository;
            public ILicenseUpdater updater;

           protected override ILicenseCatalog create_the_system_undertest(){
// Here we can get the auto mocked dependency back.
                repository = mocker.Get<ILicenseRepository>();
                updater = mocker.Get<ILicenseUpdater>();
                return mocker.ClassUnderTest;
            }
        }
    }

So far it seems great. I don’t have to explicitly mock out the dependencies, and I can only get the ones that used in this test. Its still a little work (but less) so I’m sure its a step in the right direction.
Hope this helps
Thanks
Zak

Powered by WordPress