Monthly Archives: April 2011

There are lots of different reasons why you would want to use identity impersonation in an application. The most common situation that I see is that you need to access a network resource, and you’ve been given a domain user account and password that has rights.

It would be nice to have an easy way to do the impersonation without having to do a lot of mucking around. I sat down to do this and came up with a nice, simple solution that does just that. I used this MSDN article as the basis for my solution, and there was a small amount of copying/pasting involved. I’m going to work my way backwards through the solution and then present the entire solution at the end.

What I wanted to have in the end was an extension method that could be used from any object. This was the goal usage:

In order to have the extension method available, I needed to have a static class with a static method. The static method should accept the user credentials necessary to authenticate and the actual method to be executed.

So that’s pretty easy! Now we just need to implement the GetToken method. This is the part of my solution that relies on the aforementioned MSDN article. I’ll just post the entire contents of my ExecuteAsExtension.cs file so that you can see it all:

9/28/2012 Update:
Fixed a bug in the ExecuteAs methods above where the “Action action” argument should be “Action<T> action”
Also, here’s the static class implementation provided by ericrouse in his comment. Thanks, Eric!

Share this:

Like this:

One of the most common gripes that I hear about getting started with unit testing is that the code isn’t testable or it doesn’t have a testable design. People will make claims like, “We need X hours to make the project testable before we can start writing tests.” Well, I don’t buy into that. There are techniques that you can employ to extract the pieces of code you’re modifying into little, testable nuggets that have nothing to do with the rest of the not-so-test-friendly project. I’m going to cover two of my favorite, most-commonly used techniques in this post.

Extract the code to be tested.

This is a pretty straightforward solution to a not-so-obvious problem. The most common scenario that I’ve seen for this technique is the “monster function.” I’m sure you’ve seen this before. It’s the 1000-line function that contains all the logic for the module or application you’re modifying. This is a classic hard-to-test situation because, at first glance, it seems like you need to set up everything necessary to complete the entire process in order to do any sort of unit testing.

To transform this mess into an unit testing masterpiece, you just need to do what nobody before you thought of: create a new function. Your new function can do whatever you need it to do. It can accept inputs. It can return outputs. And, it can do it all in a testable manner! So, make your function, test the hell out of it, then call your function from the appropriate place in the main function. Congratulations–you just made a unit tested change to a previously non-testable function.

Extract the code to be avoided.

The second scenario is a little more difficult, and the solution is a little less obvious. I use this technique when I’m dealing with external dependencies that aren’t enough to warrant an entire interface or when I’m working with tricky internal dependencies. Let’s look at an example. Consider the following function:

When sitting down to write a unit test for this function, you might be tempted to create a “data.xml” file in the root directory of the C drive during TestInitialize. That would probably result in a passing unit test on your machine, but please, don’t do that. You can trust that the FileStream and StreamReader objects will do their jobs correctly, so let’s just take them out of the equation for our unit testing. With a quick refactor, we end up with something like this:

Because we made our GetFileContents function virtual, the generated mock class can override its functionality. The Partial Mocks gives us this functionality; if the function were not overridden, it would be called as-is and would try to read from the hard-coded file path.

You could stick with this same approach to handle different scenarios that might arise in the isolated code. For instance, what would happen if the file did not exist? You would expect the isolated code to throw a System.IO.FileNotFoundException, right? Well, let’s test that!

The function must be internal (see next note) protected (prevents calling of the function while setting expectation) virtual (allows function to be overridden).

The target project must expose its internals to the test project. This can be done by adding the “[assembly: InternalsVisibleTo(“YourTestProjectName”)]” attribute to the target project’s assembly.info file. You can read more about this attribute here.

Share this:

Like this:

When you’re writing unit tests for your code, you want to write specific tests for specific units. Unfortunately, it is not uncommon for you code to have many external dependencies that may not be related to the functionality that you’re trying to test. This is where one of my very favorite unit testing tools, Rhino Mocks, comes into play.

Rhino Mocks is great because it allows you to mock or stub objects in your code so that you can really focus on the functionality that you’re trying to test without having to worry about doing an excessive amount of setup or external dependencies.

When you’re getting started with Rhino Mocks, one of the most confusing things that you’ll run into is that there are several different syntaxes that can be used to accomplish the same thing. The AAA (Arrange, Act, Assert) syntax is the newest and was introduced with version 3.5. The primary distinction of the AAA syntax is that you don’t need to create and manage a MockRepository object and its various states.

In this article, I will walk you through the task of writing a unit test using Rhino Mocks.

So, before we begin writing our tests, let’s look at the code we’ll be testing.

We can see that we have a Controller class that utilizes some sort of IDataSource object to check for and retrieve data. When we’re testing our controller class, we may or may not have access to our data source, though. And, even if we do have access to the data source, we may not have complete control over it. So this is an excellent situation to employ Rhino Mocks!

The first step to using Rhino Mocks is simply adding a reference to your project. Once the reference is in place, we can add the using statement to the top of our test class and get to mockin’.

Creating a mock object is extremely simple with Rhino Mocks’s AAA syntax. You just use the static MockRepository class’s GenerateMock function.

var mockDataSource = MockRepository.GenerateMock();

Now that we’ve created our mock object, we need to configure our target object to use it. In this case, our class’s IDataSource is a public property on the class. So configuring the target object is a simple assignment.

Okay, great! Our next step is to set the expectations for our mock object. For our first test, we’ll just have the call to DataAvailable return false.

mockDataSource.Expect(x => x.DataAvailable()).Return(false);

The last steps for this test are to run the function we’re testing and verify that our mock object was used as expected.

target.Process();
mockDataSource.VerifyAllExpectations();

When we run this test, the Process function will call our mock object’s DataAvailable function–which we have pre-configured to return false–and the test will pass as long as DataAvailable is called.

We can run this test, and it should pass. Awesome, now let’s write another test. This time, we’ll have DataAvailable return true. We create the mock object the same way as previously, but we’ll need to set the expectations differently.

Share this:

Like this:

Xbox LIVE Rewards is a great new program where you can earn MS Points by doing the same things you’re already doing. You can earn points by taking a monthly survey, purchasing a Gold membership, signing up for Netflix, or a number of other things.

Share this:

Like this:

Hi, I’m Adam. This is my blog.

I started this blog as a personal searchable repository of things I've learned and figured out. It evolved into a mechanism to facilitate personal growth, and now it's turned into a bit of a hobby. I enjoy writing about software development, my professional life, and related topics.

I love to hear from readers, so please feel encouraged to leave comments on anything you read here.

Follow Blog

Enter your email address to follow this blog and receive notifications of new posts by email.