tags:

views:

55

answers:

2

How do you typically TDD aspects of your application that need to access operating system's system variables?

For example, my application needs to be able to correctly retrieve the operating system's currently-logged-in user name.

So I TDD a function that does this, and it's called:

string getUserNameFromSystemEnvironment();

The problem that I have is:

I'm running the test on my machine, so I know what the user name is (say FooBar). I TDD getUserNameFromSystemEnvironment() by hardcoding FooBar in my test like.

EXPECT_EQ(getUserNameFromSystemEnvironment(), "FooBar");

Clearly, this test runs okay on my machine, but not on others. To make it run fine on
others, however, I would need to use getUserNameFromSystemEnvironment(). But then, that kind of defeats the purpose of the test because we will have:

EXPECT_EQ(getUserNameFromSystemEnvironment(), 
          getUserNameFromSystemEnvironment());

Any ideas?

+2  A: 

Just ensure a value comes back, you don't always need to know what the exact value is.

  • Check the type is a string.
  • Check it's not null or empty.

Tests don't need to be 100% perfect, they just have to increase your confidence in the code.

Chad
@Chad, "Tests don't need to be 100% perfect" <-- thanks for this insight. I never thought of it that way before.
ShaChris23
+5  A: 

If you want to check this, you would need to set up a mock. Make an interface that returns the user ID, an implementation that calls getUserNameFromSystemEnvironment(), and a mock that returns whatever string you tell it to return.

But that's not really what you want to do. If you try to test getUserNameFromSystemEnvironment(), then you're effectively testing an operating system function. You don't need to test other people's code. Instead, put getUserNameFromSystemEnvironment() into an interface, and mock that for other parts of your system. Then, for example, to test LoginValidator, pass in a mock that returns usename as "Foobar", and verify that it validates the login. Then add a test that returns a username that should not validate and verify that it doesn't let it in.

Ron Romero
+10 if I could. All so obvious when you read it written so clearly. Touching various aspects of testing. *Don't test other people's code. Write your code in such a way it can easily be mocked.*
Lieven