简体   繁体   中英

C# Create Assembly and set Version - During runtime

I'm doing Unit-Tests and I want to test this:

public static string GetVersion(Assembly assembly)
{
    return assembly.GetName().Version.ToString();
}

The Question is in the Title.

Is this even possible?

I think through reflection you can change the response of the Property but its not written to the assembly it self.

PropertyInfo nameProperty = typeof (Version).GetProperty ("Version");
FieldInfo versionField = nameProperty.GetBackingField ();
versionField.SetValue (assemby.GetName().Version, <Version you want>);

This sounds like a job for a mock object . Create a fake type that "mocks" the Assembly type, and use that fake type for testing. Much easier than trying to get the universe to bend to your will just to test that your code handles obscure corner cases.

Scout around, there are multiple libraries to create mock types. Here's one: http://msdn.microsoft.com/en-us/magazine/cc163904.aspx

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM