Is there a way to tell during exection whether code is being run from a Silverlight Unit Test Framework assembly? (For context, I am hoping to create a NinjectModule which will bind DomainClient to a FakeDomainCl开发者_运维问答ient if we're running the Unit Test project, but bind to the WebDomainClient otherwise.)
It's a bit crude, but one possibility would be to test one of the properties (probably LocalPath) from System.Windows.Application.Current.Host.Source. You would need to test whether the hosting XAP file was the XAP from your test project, or whether it was the XAP for your application. This would obviously make an assumption about XAP file names, which makes it a bit brittle (even if you derived something from the namespace, the XAP file name is actually configurable in the project properties in any case - so there's no guarantee it would always match).
Alternatively, you could test the value of System.Windows.Application.Current.RootVisual. Again, you would of course need to keep in mind that there's no guarantee that future versions of the Silverlight Unit Test Framework will use the same Microsoft.Silverlight.Testing.Client.TestPage (although implementing the check perhaps as a static extension method for the Application class, for example, would at least mean you could confine your changes to your extension method(s) in future as necessary).
Another alternative would be to use the HTML Bridge and test one of the properties from System.Windows.Browser.HtmlPage.Document.DocumentUri. This seems worse than the first two options, because assumptions about hosting uris / page names would likely be even worse than assumptions about the particular UIElement used for the Application or the name of the XAP file.
Any solution based around XAP file names or hosting page names would probably need to rely on convention-based names in any case, as you would want to use the technique in your tests across multiple modules / projects.
A better alternative would probably be to use System.Windows.Application.Current.Host.InitParams. You could potentially pass a specific param in the page within your test project, and ultimately have your code test the value of that specific param. This has the advantage that it would not require any specific RootVisual or any specific naming-convention for the XAP file name or uri / page name.
The best way is not to have to know this at all by having a good design that allows you to rebind the DomainClient in your tests rather than deciding in your production code which instance it should use. This keeps your production code free of test code and reduces the chance of strange exceptions.
A hack would be to create a static class with a static property UnitTestRunning that is false by default and set to true in the test initializer and read in the module.
精彩评论