c# - Modifying a private static readonly field -
i have large application reads parameters configuration file.
i'm writing unit tests class generates result after performing operations both parameter , value read configuration file:
internal static class password { private static readonly byte password_private_key = configfile.readbyte("password_private_key"); public static byte generate(byte passwordpublickey); } in unit test, know values password.generate() method should return given password_private_keyand password_public_key. i'd password_private_key value used defined in unit test class, not in configuration file:
[testmethod] public void passwordgenerate_calculatedproperly() { byte passwordpublickey = 0x22; password_accessor.password_private_key = 0xf0; byte expectedgenerated = 0xaa; byte generated = password_accessor.generate(passwordpublickey); assert.areequal(expectedgenerated, generated); } is there way can write private static readonly thru code, don't have rely configuration file tests?
to in clean way, need make password more testable. this, consider design:
internal static class password { public static void configure(iprivatekeyprovider keyprovider) { keyprovider = keyprovider; } public static byte generate(byte passwordpublickey); // use keyprovider private static iprivatekeyprovider* keyprovider; } internal interface iprivatekeyprovider { byte getprivatekey(); } internal class configprivatekeyprovider : iprivatekeyprovider { private static readonly byte password_private_key = configfile.readbyte("password_private_key"); public byte getprivatekey() { return password_private_key; } } internal class privatekeyproviderstub : iprivatekeyprovider { public privatekeyproviderstub(byte privatekey) { this.privatekey = privatekey; } public byte getprivatekey() { return this.privatekey; } } now production code can use configprivatekeyprovider , tests can use privatekeyproviderstub.
it bit simplified retain password static class. i'd recommend refactoring ordinary class, singleton maybe if it's appropriate.
note there many testing frameworks allow generate mocks , stubs conveniently on fly (rhino mocks example), there no need manually implement privatekeyproviderstub.
Comments
Post a Comment