2

For my unit test, I'm trying to use constants from a static class (ModelConstants) of my main project in my testing project.

int ones = ModelConstants.PLOT_STORE_PRECISION_FACTOR * ModelConstants.RECENT_SAMPLES;

When trying to run this test method, I get a TypeInitializationException on the line above. InnerException is a FileNotFoundException saying the assembly System.Windows could not be found. This makes no sense to me, but I guess the static constants class could somehow not be initialized correctly. What could be the reason for this?

Btw, I can instantiate non-static classes of my main project without any problems.

Edit:

The constants are defined as follows:

public static readonly int TRACKING_INTERVAL = 200;
public static readonly int SAMPLE_WINDOW = 3;
public static readonly int PLOT_STORE_PRECISION_FACTOR = 1000 / TRACKING_INTERVAL;
Cedric Reichenbach
  • 8,970
  • 6
  • 54
  • 89

2 Answers2

3
public static readonly int TRACKING_INTERVAL = 200;
public static readonly int SAMPLE_WINDOW = 3;
public static readonly int PLOT_STORE_PRECISION_FACTOR = 1000 / TRACKING_INTERVAL;

Those are not constants. These are class static fields. When such a field is being read, the static class constructor is invoked. There you have your TypeInitializationException, which throws on type initialization. The reason is in the InnerException.

Instead, I would recommended using constants:

public const int TRACKING_INTERVAL = 200;
public const int SAMPLE_WINDOW = 3;
public const int PLOT_STORE_PRECISION_FACTOR = 1000 / TRACKING_INTERVAL;

These are checked and accessed at compile time and may even increase performance.

Erik Philips
  • 53,428
  • 11
  • 128
  • 150
AgentFire
  • 8,944
  • 8
  • 43
  • 90
  • Cool, changing `static readonly` to `const` (where possible) did the trick. The original reason I had used `readonly` was because I'm home in Java and searched for an alternative for `final static` and found this thread: http://stackoverflow.com/questions/1327544/what-is-the-equivalent-of-javas-final-in-c :) – Cedric Reichenbach Sep 17 '13 at 19:34
  • 2
    @CedricReichenbach - For what it's worth, if you want a "constant" class variable, you *have* to declare it as `static readonly` instead of `const`. You can only use `const` for value types. – Bobson Sep 18 '13 at 13:25
1

From the data you presented, the only possible reason I see for the error is that the ModelConstants class has a static constructor which, for some reason, throws an exception in the test project only.

It could be that the constructor accesses some global state that is not initialized in the test project.

Cristian Lupascu
  • 39,078
  • 16
  • 100
  • 137