1

I'm writing a set of unit tests to test a CRUD system.

I need to register a user in Test1 - which returns a ServiceKey I then need to add data in Test2 for which I need the ServiceKey

What is the best way to pass the ServiceKey? I tried to set it in the TestContext, but it just seems to disappear between the tests.

p.s.w.g
  • 146,324
  • 30
  • 291
  • 331
GreyCloud
  • 3,030
  • 5
  • 32
  • 47

2 Answers2

2

You should not share aany state between unit tests, one of the very important properties of good unit tests - Independency. Tests should not affect each other.

See this StackOverflow post: What Makes a Good Unit Test?

EDIT: Answer to comment

To share a logic/behaviour (method) you can extract the common code into a helper method and call it from different tests, for instance helper method which creates an user mock:

private IUser CreateUser(string userName)
{
    var userMock = MockRepository.GenerateMock<IUser>();
    userMock.Expect(x => x.UserName).Return(userName);
    return userMock;
}
Community
  • 1
  • 1
sll
  • 61,540
  • 22
  • 104
  • 156
0

the idea of unit tests is that each tests checks one functionality. if you create dependencies in between your tests it is no longer certain that they will pass all the time (they might get executed in a different order, etc.).

what you can do in your specific case is keeping your Test1 as it is. it only focuses on the functionality of the registering process. you don't have to save that ServiceKey anywhere. just assert inside the test method.

for the second test you have to setup (fake) everything you need it to run successfully. it is generally a good idea to follow the "Arrange Act Assert"-Principle, where you setup your data to test, act upon it and then check if everything worked as intended (it also adds more clarity and structure to your tests).

therefore it is best to fake the ServiceKey you would get in the first test run. this way it is also much easier to controll the data you want to test. use a mocking framework (e.g. moq or fakes in vs2012) to arrange your data they way you need it. moq is a very lightweight framework for mocking. you should check it out if you are yet not using any mocking utilities.

hope this helps.

Thomas Mondel
  • 1,944
  • 3
  • 20
  • 25