问题
I have a member that returns a string from a resource file, and I want to unit test this, as there's quite a few and they could be changed by mistake. I understand that this is achievable using reflection but I've been asked to do it in a way that doesn't use reflection.
The members look something like this;
protected override string StringOne
{
get
{
return Resources.String;
}
}
I understand that setting up the return for the member can be done as;
mock.Protected()
.Setup<string>("StringOne")
.Returns("Returned string.");
and .verifiable() can be added to the end of this. But I can't find how to verify that a string is being returned. Or am I right in thinking that the by setting this up with .verifiable(), that the .returns("") value is the expected, and calling
mock.Verify();
will verifying that the member has returned the correct string or simply that the member was called at some point during the test?
回答1:
The problem that you are encountering here is that you are trying to test something that isn't available from outside of the class. Tests should only test the public interface of your class so that the internals of the class can change as long as the public behaviour remains the same.
In this instance, I think that you have two options:
One is to move this code into another class with these properties being public, that way your test can just call the new public properties and check the return and the classes that need to use the value of the property can call your new class. Inheritance is generally not a great way of sharing code anyway (a blog post explaining this concept: http://www.blinkingcaret.com/2016/04/13/composition-superior-inheritance/)
The other is to test where these properties end up being used. For example, if you have some method that passes the value of StringOne
into another mocked class, you can check that the correct value is passed through or if it ends up being used in a file path, you should test that the file path ends up being correct etc
来源:https://stackoverflow.com/questions/41161353/mocking-a-protected-member-without-reflection