hokapoka
hokapoka

Reputation: 479

C# UnitTest Share single instance of an object across Unit Tests

I'm trying to write some TestMethods in a UnitTests that all share a single instance of a public static resource.

In the constructor of my Unit Test I instantiate a public static that's in another C# project. Then all of my tests access this public static.

However it appears that a new instance of the Test Class is instantiated for each TestMethod, within that UnitTest class.

Is there a means of allowing these tests to share the same instance of the public static?

Or is there another technique I should be using to test a service?

** UPDATE **

Okay it appears that I'm using the wrong approach for what I want to achieve.

I already have UnitTests in place that are testing, in isolation and without any shared resources, that are working as expected.

What I am trying to achieve is a means to test concurrent connections to a service that will be Exposed via either a Web Service / HTTP interface or direct connection through TcpListener to pass serialized byte[].

Each of the connected clients are interacting with one-another, through the service.

These tests are solely to test reliance and interoperability of virtual clients at a level lower than the exposed network interfaces.

The service has been wrapped into some public static objects that expose the same functionality as will be exposed via the network interfaces.

I need a way to create virtual clients that will connect to these objects and assert different outcomes based on the responses.

Upvotes: 2

Views: 2773

Answers (1)

cdeszaq
cdeszaq

Reputation: 31320

In general, you don't want unit tests to share ANY state, that way there are fewer possibilities of fall-through errors. You should be setting up the expected start state for each test to eliminate these fall-through issues.

So, for example, if you need a shared static SomethingOrOther, then create a new one in the correct state for each unit test.

Upvotes: 6

Related Questions