Unit Testing Abstract classes

Opinions wanted: How do you write unit tests for abstract (MustInherit in VB.NET) classes? Do you derive a simple class off your abstract class in your unit test assembly? Or do you just write unit tests for the derived classes? Hmmm.....

Published Thursday, December 18, 2003 2:30 PM by PSteele

Comments

# re: Unit Testing Abstract classes

I'm nerw to this test stuff...

Wouldn't it make sense to have a test that tries to create an instance where failure is sucess because the class is abstract.

Thursday, December 18, 2003 2:34 PM by AndrewSeven

# re: Unit Testing Abstract classes

I usually create a concrete type for specifically for my unit test that adds basic behavior that allows me to accurately test the functionality of the abstract class.

Thursday, December 18, 2003 2:45 PM by Drew Marsh

# re: Unit Testing Abstract classes

AndrewSeven,

My abstract class contains some functionality that I want to test. So I need to instantiate something to test it, but the class is abstract.

I like Drew's suggestion. That's what I was leaning towards.

Thursday, December 18, 2003 3:25 PM by Patrick Steele

# re: Unit Testing Abstract classes

Ya, I thought of that, but if you create a class just to test the abstract class, shouldn't it be "in" the test, not in the project?

Surely you have classes that inherit from the abstract class?

Thursday, December 18, 2003 3:40 PM by AndrewSeven

# re: Unit Testing Abstract classes

I think we're saying the same thing. I create a concrete class "in" my unit test project. That concrete class is throw away and only serves as a stub that maybe does some Debug.WriteLine'ing. It's definitely not an easy scenario to test. Have a look at this paper[1] on Mock Objects. While not exactly the same, it's somewhat related.

[1] http://www.sidewize.com/company/mockobjects.pdf

Thursday, December 18, 2003 5:05 PM by Drew Marsh

# re: Unit Testing Abstract classes

Why don't you create a mock object (in your test project) that inherits from you abstract base class. The abstract methods could return defaults (null for reference types, defaults for value types) if they expect a return value, or have an out (or ref) parameter. You probably will only be interested in testing the non-abstract methods, right?

Thursday, December 18, 2003 6:28 PM by Yves Reynhout

# re: Unit Testing Abstract classes

You might want to take a look at this article:
http://msdnaa.net/Resources/display.aspx?ResID=2364

Friday, December 19, 2003 3:57 AM by Roy Osherove