The other answers have already shown how you can mock a property chain to work around your problem.
But the real problem here is that unit testing and mocking don't really work well if you violate the law of demeter. If you want your code to be testable and maximally reusable, then you need to directly inject the real dependencies of your code and hide those dependencies behind abstractions.
For example, instead of doing this:
public class MyClass
{
public ControllerContext Context { get; set; }
public void DoSomething()
{
// BAD: we're only interested in the name, but instead we've injected
// a ControllerContext that can give us a HttpContext that can give us
// a User that can give us an Identity that can give us the Name.
string name = Context.HttpContext.User.Identity.Name;
// etcetera
}
}
Do this:
public class MyClass
{
public INameProvider NameProvider { get; set; }
public void DoSomething()
{
// GOOD: we've injected a name provider
string name = NameProvider.Name;
// etcetera
}
}
By introducing the INameProvider
concept, your component code, tests and mocks become much simpler. Your code also becomes more reusable: it only has a dependency on the abstract concept of a "name provider", rather than on a bunch of ASP.NET classes. You will be able to reuse your component in any environment as long as it is possible to implement a INameProvider
adapter.
The trade-off is that you will need to declare the INameProvider
interface and write a wrapper class which implements it. When you consistently follow this approach, you will end up with a lot of small interfaces and adapter classes. Such is the way of test driven development.
(In case you're wondering why I introduce INameProvider
instead of setting the name directly - this is so that the IoC container can use the interface to match up the dependency with the implementation.)