Unit testing passing arguments to base constructor - c#

I have the following code:
using System;
using NUnit.Framework;
using Rhino.Mocks;
public class A
{
}
public class B
{
}
public interface IStatementExecutor
{
void Exec(string statement);
}
public abstract class Foo<T>
{
private readonly IStatementExecutor _statementExecutor;
private readonly string _targetSegment;
protected Foo(IStatementExecutor statementExecutor, string targetSegment)
{
_statementExecutor = statementExecutor;
_targetSegment = targetSegment;
}
public void Update(T item)
{
_statementExecutor.Exec("sp_" + _targetSegment + "Update");
}
}
public class Bar : Foo<A>
{
public Bar(IStatementExecutor statementExecutor)
: base(statementExecutor, "ATable")
{
}
}
public class Baz : Foo<B>
{
public Baz(IStatementExecutor statementExecutor)
: base(statementExecutor, "BTable")
{
}
}
[TestFixture]
public class Foo_Tests
{
[Test]
public void Update_CallsStatementExecutorWithTableName()
{
const string tableName = "TestTable";
var mockStatementExecutor = MockRepository.GenerateMock<IStatementExecutor>();
mockStatementExecutor.Expect(m => m.Exec("sp_" + tableName + "Update"));
var sut = MockRepository.GeneratePartialMock<Foo<A>>(mockStatementExecutor, tableName);
var testModel = new A();
sut.Update(testModel);
mockStatementExecutor.AssertWasCalled(m => m.Exec("sp_" + tableName + "Update"));
}
}
I already have unit tests for the base class Foo<T>. Since the base class is already covered, I don't want to write identical tests for the derived classes Bar and Baz.
The only thing I really care about in the derived classes is that the correct string target is passed to the base class.
I'm struggling on how to unit test this without breaking encapsulation of the derived classes or writing redundant unit tests.
So, the question is, how do I test that the correct value gets passed to the base class from the derived classes for the target parameter?
(If your answer is "use composition...", please back it up with a code sample modified from above.
Thanks!

Think I'be more likely to test through the other methods on Bar and Baz, as you'd expect something bad to happen if you'd put ZTable in there instead of BTable
You could add a method to Foo that would return what ever had been passed to it
and then after creating the descendant call it and validate against the expected value.
Or you could do something like
public class Bar : Foo<A>
{
private static String _tableName = "ATable";
public String TableName {get {return _tableName;}}
public Bar() : base(_tableName)
{
}
}
Then you could test testBar.TableName
Another Option would be T was a struct or a class with a TableName property, then you wouldn't need Bar and Baz descendants, just for this.

Your Foo and Bar unit test methods could call helper methods that contain the common testing code.

You can do this in many ways. One way you could use a mocking framework like TypeMock to effectively mock the based class and thus get more information from TypeMock about internal variables.
It't not apparently clear from your post, though, why it's important that the base class be used in a specific why by the bar class. This isn't clear because you have no way of testing it. i.e. there's no external behaviour that you can monitor to guarantee Bar is using Foo in the expected way. You could redirect console output then monitor that output to do the verification. But, I don't think that's really what you're looking for.
You should provide an more testable example; something that doesn't just output text, something that had real behaviour that you can observe by a test.

Related

Moq tell if function was called [duplicate]

I have a base class:
public abstract class MyBaseClass
{
protected virtual void Method1()
{
}
}
and a derived class:
public class MyDerivedClass : MyBaseClass
{
public void Method2()
{
base.Method1();
}
}
I want to write a unit test for Method2 to verify that it calls Method1 on the base class. I'm using Moq as my mocking library. Is this possible?
I came across a related SO link:
Mocking a base class method call with Moq
in which the 2nd answer suggests it can be achieved by setting CallBase property to true on the mock object. However it's not clear how this would enable the call to the base class method (Method1 in the above example) to be verified.
Appreciate any assistance with this.
Unit tests should verify behavior, not implementation. There are several reasons for this:
The results are the goal, not how you get the results
Testing results allows you to improve the implementation without re-writing your tests
Implementations are harder to mock
You might be able to put in hooks or create mocks that verify that the base method was called, but do you really care how the answer was achieved, or do you care that the answer is right?
If the particular implementation you require has side effects that you can verify, then that is what you should be validating.
Mocking the base class from the perspective of the derived class is not possible. In your simple example, I would suggest one of the two options.
Option 1: In the event that MyDerivedClass really shouldn't care what MyBaseClass is up to, then use dependency injection! Yay abstraction!
public class MyClass
{
private readonly IUsedToBeBaseClass myDependency;
public MyClass(IUsedToBeBaseClass myDependency){
_myDependency = myDependency;
}
public void Method2()
{
_myDependency.Method1();
}
}
Elsewhere in test land...
[TestClass]
public class TestMyDependency {
[TestMethod]
public void TestThatMyDependencyIsCalled() {
var dependency = new Mock<IUsedToBeBaseClass>();
var unitUnderTest = new MyClass(dependency.Object);
var unitUnderTest.Method2();
dependency.Verify(x => x.Method1(), Times.Once);
}
}
Option 2: In the event that MyDerivedClass NEEDS to know what MyBaseClass is doing, then test that MyBaseClass is doing the right thing.
In alternative test land...
[TestClass]
public class TestMyDependency {
[TestMethod]
public void TestThatMyDependencyIsCalled() {
var unitUnderTest = new MyDerivedClass();
var unitUnderTest.Method2();
/* verify base class behavior #1 inside Method1() */
/* verify base class behavior #2 inside Method1() */
/* ... */
}
}
What you're describing is not a test of your code, but a test of the behavior of the language. That's fine, because it's a good way to ensure that the language behaves the way we think it does. I used to write lots of little console apps when I was learning. I wish I'd known about unit testing then because it's a better way to go about it.
But once you've tested it and confirmed that the language behaves the way you expect, I wouldn't keep writing tests for that. You can just test the behavior of your code.
Here's a real simple example:
public class TheBaseClass
{
public readonly List<string> Output = new List<string>();
public virtual void WriteToOutput()
{
Output.Add("TheBaseClass");
}
}
public class TheDerivedClass : TheBaseClass
{
public override void WriteToOutput()
{
Output.Add("TheDerivedClass");
base.WriteToOutput();
}
}
Unit test
[TestMethod]
public void EnsureDerivedClassCallsBaseClass()
{
var testSubject = new TheDerivedClass();
testSubject.WriteToOutput();
Assert.IsTrue(testSubject.Output.Contains("TheBaseClass"));
}

Intercept Method/Property call in c#

In the code below I have a class Foo which is called (without an interface) by my main method. There is no backing field or setter for the property, instead it calls a private method. Foo cannot be changes, nor can the usage of foo be changed to an IFoo interface.
- How do I change the value of foo.FooValue?
- Is there anything in the System.Reflection, System.Reflection.Emit, .NET standard libraries etc (unsafe code, whatever) that I can include in a unit test to change the return value?
I appreciate if there is something it's bound to be quite "evil", but I am interested in "evil" answers.
public class Program
{
public static void Main(){
Foo foo = new Foo();
int bar = foo.FooValue;
}
}
public class Foo{
public int FooValue
{
get
{
return this.FooMethod();
}
}
private int FooMethod
{
return 0;
}
}
Related questions:
How to set value of property where there is no setter - Related but unanswered - Maybe the answer is "no", but I'm not convinced by the top answer which merely points out you can't achive this by changing a (non-existent) backing field.
Intercept call to property get method in C# - Interesting. Not sure whether this is my answer and if it is, not sure how it could be used in a unit test.
EDIT: Okay. I'm going to re-write my code to make it more testable. However, out of interest, has anyone out there successfully hacked their way through this situation?
You could create a proxy for Foo that could be mocked:
public class FooProxy : IFoo
{
private Foo _Foo;
public FooProxy(Foo foo)
{
_Foo = foo;
}
public int FooValue
{
get {return _Foo.FooValue();
}
}
public interface IFoo
{
public int FooValue {get;}
}
then you can use DI to "inject" an IFoo and make your code more testable.

C#: Giving access to private members without 3-fold code duplication

I have a class
public class Foo{
public Foo{...}
private void someFunction(){...}
...
private Acessor{
new Acessor
}
}
with some private functionality (someFunction). However, sometimes, I want to allow another class to call Foo.SomeFunction, so I have an inner class access Foo and pass out that:
public class Foo{
public Foo{...}
private void someFunction(){...}
...
public Acessor{
Foo _myFoo;
new Acessor(Foo foo){_myFoo = foo;}
public void someFunction(){
_myFoo.someFunction();
}
}
}
With this code, if I want a Foo to give someone else pemission to call someFunction, Foo can pass out a new Foo.Accessor(this).
Unfortunately, this code allows anyone to create a Foo.Accessor initiated with a Foo, and they can access someFunction! We don't want that. However, if we make Foo.Accessor private, then we can't pass it out of Foo.
My solution right now is to make Acessor a private class and let it implement a public interface IFooAccessor; then, I pass out the Foo.Accessor as an IFooAccessor. This works, but it means that I have to declaration every method that Foo.Accessor uses an extra time in IFooAccessor. Therefore, if I want to refactor the signature of this method (for example, by having someFunction take a parameter), I would need to introduce changes in three places. I've had to do this several times, and it is starting to really bother me. Is there a better way?
If someFunction has to be accessible for classes in the same assembly, use internal instead of private modifier.
http://msdn.microsoft.com/en-us/library/7c5ka91b(v=vs.71).aspx
If it has to be accessible for classes which are not in the same assemble then, it should be public. But, if it will be used by just a few classes in other assemblies, you probably should think better how you are organizing you code.
It's difficult to answer this question, since it's not clear (to me at least) what exactly you want to achieve. (You write make it difficult for someone to inadverdantly use this code in a comment).
Maybe, if the method is to be used in a special context only, then explicitly implementing an interface might be what you want:
public interface ISomeContract {
void someFunction();
}
public class Foo : ISomeContract {
public Foo() {...}
void ISomeContract.someFunction() {...}
}
This would mean, that a client of that class would have to cast it to ISomeContract to call someFunction():
var foo = new Foo();
var x = foo as ISomeContract;
x.someFunction();
I had a similar problem. A class that was simple, elegant and easy to understand, except for one ugly method that had to be called in one layer, that was not supposed to be called further down the food chain. Especially not by the consumers of this class.
What I ended up doing was to create an extension on my base class in a separate namespace that the normal callers of my classes would not be using. As my method needed private access this was combined with explicit interface implementation shown by M4N.
namespace MyProject.Whatever
{
internal interface IHidden
{
void Manipulate();
}
internal class MyClass : IHidden
{
private string privateMember = "World!";
public void SayHello()
{
Console.WriteLine("Hello " + privateMember);
}
void IHidden.Manipulate()
{
privateMember = "Universe!";
}
}
}
namespace MyProject.Whatever.Manipulatable
{
static class MyClassExtension
{
public static void Manipulate(this MyClass instance)
{
((IHidden)instance).Manipulate();
}
}
}

How to test virtual methods using Moles?

How can I test the IsHappy function using Moles?
class SomeClass
{
protected virtual bool IsHappy(string mood)
{
return (mood == "Happy");
}
}
I tried to test if by using Stub:
SSomeClass stub = new SSomeClass();
stub.CallBase = true;
Assert.IsTrue(stub.IsHappyString("Happy"));
... but the IsHappyString method returns null thus throwing a NullReference exception.
So, how can I test the default implementation of IsHappy method?
I'd forget about stubs here. Stubs/mocks are for when you want to fake the behavior of a dependency. You'd stub your SomeClass if had SomeClassClient that you wanted to test and it used SomeClass:
public class Foo
{
public virtual int GetFoosInt()
{
return 12;
}
}
public class FooClient
{
private Foo _foo;
public FooClient(Foo foo)
{
_foo = foo;
}
public int AddOneToFoosInt()
{
return _foo.GetFoosInt() + 1;
}
}
In this example, when testing FooClient, what you want to test is that it returns one more than "GetFoosInt()". You don't actually care what FoosInt is for testing the FooClient. So, you create a Foo stub where you can setup GetFoosInt to return whatever you want.
In your case, testing a protected virtual member, I'd go with this:
[TestClass]
public class SomeClassTest
{
private class DummySomeClass : SomeClass
{
public bool IsHappyWrapper(string mood)
{
return IsHappy(mood);
}
}
[TestMethod]
public void SomeTest()
{
var myClass = new DummySomeClass();
Assert.IsTrue(myClass.IsHappyWrapper("Happy"));
}
}
This gives you 'direct' access to the protected virtual to test default behavior. Only word of caution is that if you start defining abstract members and adding to SomeClass in general, you'll have to add them to this dummy inheritor as well, adding to testing maintenance overhead.
The purist in me says that you should leave protected members alone and only test them through the public interface. But, that may or may not be practical in your situation, and I don't really see any harm in this approach.
Stubs and Moles are for isolating a class from any dependencies it has, either environmental dependencies or class dependencies. This class has no dependencies whatsoever, so why are you trying to mole or stub it?
If you want to make sure this base class works properly when people override it, then you'll need to create a test implementation. In that case this is more or less what your test cases should look like:
public SomeClassTestAdapter : SomeClass
{
public bool GetIsHappy(string mood)
{
return IsHappy(mood);
}
}
[Test]
public void ShouldReturnTrueWhenPassedHappy()
{
var classUnderTest = new SomeClassTestAdapter();
bool result = classUnderTest.IsHappy("Happy");
Assert.IsTrue(result, "Expected result to be true");
}
[Test]
public void ShouldReturnFalseWhenPassedLowerCaseHappy()
{
var classUnderTest = new SomeClassTestAdapter();
bool result = classUnderTest.IsHappy("happy");
Assert.IsFalse(result, "Expected result to be false");
}
[Test]
public void ShouldReturnFalseWhenPassedNull()
{
var classUnderTest = new SomeClassTestAdapter();
bool result = classUnderTest.IsHappy(null);
Assert.IsFalse(result, "Expected result to be false");
}
Etc.
There is no place in this code that stubs or moles should be squeezed in.
If you don't want to create an adapter class for this case, you can use built-in .Net features rather than a big, paid dependency like Moles. Reflections and dynamic let you get access to protected or private members. See this example:
http://igoro.com/archive/use-c-dynamic-typing-to-conveniently-access-internals-of-an-object/

How can I inherit an inner class using an abstract base class?

I'm trying to create a test class which organizes its test methods using inner classes. I would like for this class to be abstract with the ability to set a static property so this property can be injected. Here's an example of what I'm talking about:
[TestClass]
public abstract class BaseUnitTest
{
public static string InjectedProperty;
public static string GetInjectedString()
{
return InjectedProperty;
}
[TestClass]
public class WhenFoo
{
[TestMethod]
public void TestFoo()
{
string str = GetInjectedString();
}
}
}
[TestClass]
public class DeriverdUnitTest : BaseUnitTest
{
[ClassInitialize]
public void SetUp()
{
InjectedProperty = "Injected Property";
}
}
However, I don't see a DerivedUnitTest+WhenFoo+TestFoo() class show up in my unit test view. I'm using Visual Studio 2010. I'm guessing when I override BaseUnitTest, I don't override its inner classes as well. I suppose I could make its inner classes abstract and override them later, but as the complexity of my test class increases this will get really annoying. Could somebody please explain why this is occuring and how I can fix it?
Thanks.
Edit:
I feel like I need to better explain my reasons for wanting to do this. We'd like to implement a testing standard which is very verbose in its naming. Therefore a test class would look something like this:
[TestClass]
public abstract class BaseUnitTest
{
public static string InjectedProperty;
public static string GetInjectedString()
{
return InjectedProperty;
}
[TestClass]
public class WhenFooIsCalled
{
[TestClass]
public class AndTheArgumentIsNull
{
[TestMethod]
public void AnArgumentNullExceptionShouldBeThrown()
{
string str = GetInjectedString();
}
}
}
}
The advantage of this is when you open up the test view in Visual Studio and display the method name and class name columns you get something that looks like this:
BaseUnitTest+WhenFooIsCalled+AndTheArgumentIsNull AnArgumentNullExceptionShouldBeThrown()
This makes it a lot easier to glance to tell what a failing test among a few hundred pass tests is supposed to do.
The main reason I want to be able to override the abstract BaseUnitTest is because when I do all of the tests which were contained in the BaseUnitTest are all added to the DerivedUnitTest and show up in the Test View in Visual Studio.
Thanks again.
In the C# language, nested classes have no special relationship with the class in which they are nested. It is a completely different type. There is only one good reason you'd ever do this: you can declare the class private. Which helps you to create a little worker class to get a job done on behalf of the outer class, a class that is completely invisible from the outside. Very useful, you cannot otherwise declare a private class at outer class scope, the best you can do is internal.
What follows is that it in no way plays a role in the inheritance of the outer class. A class you derive from the outer has no visibility to the nested class inside the base class at all. Which was the intention, declaring it private was the reason to nest it in the first place.
Punt: if you need that class in the derived one just declare it internal or public.
Nested types don't work that way. You can't "override" types.
It's not clear what you're trying to achieve here, but I don't think it's going to work.
You can accomplish the kind of rich, verbose, BDD-style test repriting with xUnit.NET and SubSpec. SubSpec is included in the xUnit.NET extras download these days. You can read more about SubSpec and BDD testing at the following article:
http://haacked.com/archive/2008/08/24/introducing-subspec.aspx
How about using a config file? For Example
[TestClass]
public class WhenFoo
{
[TestMethod]
public void TestFoo()
{
string str = ConfigurationManager.AppSettings["WhenFooTestFooString"];
}
}

Categories

Resources