Is it possible to mock the is
operator? In my code I have logic depending on what type of class it is, but the value itself is stored in the class as the common interface.
Basically, what I want to do is return true
by defining the mock to be of IValue
, but return true
for is Value
public class Value : IValue
{
}
public interface IValue
{
}
public class Tester
{
public bool CheckIfValue(IValue value)
{
return value is Value;
}
}
[Test]
public void TestIfValue()
{
Tester tester = new Tester();
var value = MockRepository.GenerateStub<IValue>();
// can I add anything here which will make CheckIfValue return true?
bool isValue = tester.CheckIfValue(value);
Assert.That(isValue, Is.True);
}
No it is not possible to "mock" the is
operator, is
will return only true in the following cases:
Your design is bad, you shouldn't require any IValue
if you actually need it to be an instance of Value
.
The point is to depend on abstractions and not the implementation, that's why you have the IValue
interface to start with. Tester
shouldn't care if it gets a Value
, MockValue
or anything else, it should just depend on the methods and properties defined in the IValue
interface.
The point to creating a mock is to test the behavior of your Tester
class in a specific scenario, the mock allows you to specify the behavior of the object Tester
receives for that test without having to create lots of dummy classes such as class FakeValueWhichDoes... : IValue
in order to test it.