I would like to be able to mock the ClientScriptManager class on a webforms Page object,
however it seems like I can’t, I get the error that I can’t mock a sealed class.
MockRepository mocks = new MockRepository()
Page page = mocks.PartialMock<Page>();
var clientScript = mocks.PartialMock<ClientScriptManager>(); //error here
SetupResult.For(page.ClientScript).Return(clientScript);
Any advice on how to mock the clientscriptmanager would be appreciated.
As you’ve discovered, you can’t use most mocking libraries to mock sealed types. One reason for this is that many mock libraries operate by creating a derived type but if the class is sealed then they can’t derive from it.
What we’ve done internally at Microsoft is that we use a hand-written
IClientScriptManagerinterface and then use aClientScriptManagerWrapperthat implements that interface and delegates all calls to a realClientScriptManager.Then whatever type needs to use the
ClientScriptManagerit will instead have a reference to anIClientScriptManager. At runtime we create aClientScriptManagerWrapper(and pass in the realClientScriptManager). At test time we use a mock object library to create a mockIClientScriptManagerand use that instead.And here’s a code sample:
You can then modify the
IClientScriptManagerinterface and theClientScriptManagerWrapperto have whatever methods you need.