5
votes

I have an issue where a simple Rhino Mock stub method will work perfectly fine when I run a unit test, but will throw the exception Can't create mocks of sealed classes when executed in debug mode. I've tried replacing the Do with a Return method, but that hasn't changed the behaviour.

Using C# with Rhino Mocks 3.6, apologies for offending anyone by making an Add function subtract in a unit test ;)

Interface

public interface ICalculator
{
    int Add(int value, int value2);
}

Classes

public class Calculator : ICalculator
{
    public int Add(int value, int value2)
    {
        return value + value2;
    }
}

public class Sums
{
    private ICalculator calculator;

    public Sums(ICalculator calculatorArg)
    {
        calculator = calculatorArg;
    }

    public int Add(int value, int value2)
    {
        return calculator.Add(value, value2);
    }
}

Unit Test

[TestMethod()]
public void AddTest()
{
    //ARRANGE
    var calculatorArg = MockRepository.GenerateMock<ICalculator>();

    Func<int, int, int> subtract = delegate(int valueArg, int value2Arg)
    {
        return valueArg - value2Arg;
    };
    calculatorArg.Stub(x => x.Add(-1,-1)).IgnoreArguments().Do(subtract);

    Sums target = new Sums(calculatorArg);

    int value = 5;
    int value2 = 3;
    int expected = 2;

    //ACT
    int actual = target.Add(value, value2);

    //ASSERT
    Assert.AreEqual(expected, actual);
}
2
What version of .NET framework? This code works fine for me in both modes under .NET 4.0 (and Rhino.Mocks 3.6). What happens if you use GenerateStub instead of GenerateMock?PatrickSteele
@PatrickSteele Hmm you are correct, I recreated the project and it is working. A visual check between my original and new test projects shows up no changes- both are using the same file structure/contents and .Net framework (4.0). I'll do a full comparison and will post backkeith

2 Answers

6
votes

Just had this exact problem. I deleted the hidden .suo file and sure enough it worked.

That's when i realized that by deleting the settings the exception catching options were also deleted. It was not stopping on any exception. Re-enabling the option in "Debug"->"Exceptions..." made the error re-appear.

It is however a First Chance exception so a simple F5 (Continue) will step over it and the code runs actually as expected.

So in short, the solution of deleting the suo file, means reset settings and thus ignore exception.

2
votes

Delete the suo file

Explanation: After PatrickSteele kindly pointed out to me that creating a fresh project with my code does actually work I compared every file in the original and new projects and found that only the suo files were different. (other than Guids, project names etc).

After deleting the .suo file for the solution the problem was solved. Not my favourite answer to this question, but an answer none-the-less.