How to test a function that has .base() call - c#

I would like to do a unit test to a function that has a call to the base class inside it implementation (using .base() )
I cannot use Mocking as this is inheritance we dealing with, so I don't get the object in my constructor.
Example code:
protected override BuyerDeal Map(BuyerDealDTO buyerDealDTO, BuyerDeal buyerDealEntity)
{
buyerDealEntity.prop1 = buyerDealDTO.prop2;
base.Map(buyerDealDTO, buyerDealEntity);
return buyerDealEntity;
}
I would like to test this function but I don't want this:
base.Map(buyerDealDTO, buyerDealEntity);
to occur, as I test the base by itself.
Yet i do want to test ( Verify ) the call, and solely, the call to the base .
btw, the base class is abstract.
The problem is that if there is few classes that inherit from that base class this will result in testing the base class more than once .

Without knowing much about your mapper there might be several ways to do that:
Split your code and the map code into separate methods, e.g:
protected override BuyerDeal Map(BuyerDealDTO buyerDealDTO, BuyerDeal buyerDealEntity)
{
ExtraLogic(...);
base.Map(buyerDealDTO, buyerDealEntity);
return buyerDealEntity;
}
protected void ExtraLogic(...)
{
buyerDealEntity.prop1 = buyerDealDTO.prop2;
}
then you can test ExtraLogic. This might not work for all code as calling base may be required as a dependency, which changes the flow, as stated by comments.
I generally would not recommend that.
Or don't inherit from the base class. Inherit from the Interface and mock your abstract class then. Favour composition over inheritance (FCoI).
This allows you to inject the base class and test your code only.
Might not work if no interface is defined (which is bad anyway) or if the framework uses the abstract class explicitly.

I see three approaches:
Try to ignore the base class in derived classes' tests. Problem here is that your tests are incomplete, because you never test the interaction of derived classes' code with the base class.
Parallel inheritance hierarchies for test fixtures, i.e. an abstract fixture for the base class, which is inherited by all fixtures for derived classes. This helps to remove duplication and tests the above mentioned interaction, but makes the fixtures hard to understand.
Follow Composition over Inheritance whenever possible. No base classes, no headaches.
I would suggest to follow the third one, especially as it looks as if the mapping between buyer deals might be considered a separate responsibility anyway.
Bottom line: Just create a BuyerDealMapper, test that, and mock it when you test the other classes.

When unit testing, you are in fact testing that the code under test gives the correct output for the corresponding input.
This input may come in the form of dependencies, such as method parameters, data read from the file system or from a network source.
The output may come in the form of a value returned from the method, data written to the file system or properties passed into another class for instance.
As long as your input produces the expected output, within reason, anything else that happens in that code under test does not matter.
In your posted code, your unit test should not care whether or not the call to base.Map(buyerDealDTO, buyerDealEntity); is made or not - just that the code under test gives the expected output.
If perhaps your base class itself requires dependencies, such as file system writes or network reads etc..., these can be mocked in your test start up routines.
If you are worried that you are testing the base class multiple times, this is actually a very good thing! The more times code is tested, the more conditions and situations a piece of code sees, the more thorough, the more bullet-proof that piece of code will be. Your unit test should help guarantee that your base class code and cope with your inherited classes use of it.
For instance, how will your method cope if the base class throws an exception? Returns an unexpected value? Doesn't return for one reason or another? Unit testing should take these things into account.
Of course, if the base class call has no relevance to the method and how it works, then perhaps it shouldn't be called in that method at all. Some code refactoring may be required to fix this. This, in fact, is a huge benefit of unit testing as it can also help you with architectural issues such as this. Of course, assuming you are using TDD - rather than testing pre-written code - this can be a big help.
Refactoring
A potential way of refactoring this code is to not call the base class method in your overriden method. Have the base class ensure this method is called itself, and then in the overridden code call the code that is required. For instance:
public abstract class MyBaseClass
{
public BuyerDeal Map(BuyerDealDTO buyerDealDTO, BuyerDeal buyerDealEntity)
{
// perform base class logic here
var entity = this.MapInternal(buyerDealDTO, buyerDealEntity);
return entity;
}
protected abstract BuyerDeal MapInternal(BuyerDealDTO buyerDealDTO, BuyerDeal buyerDealEntity);
}
public class MyClass : MyBaseClass
{
protected override BuyerDeal MapInternal(BuyerDealDTO buyerDealDTO, BuyerDeal buyerDealEntity)
{
buyerDealEntity.prop1 = buyerDealDTO.prop2;
return buyerDealEntity;
}
}
Using this method, when you unit test MyClass, you are no longer testing MyBaseClass::Map(...) multiple times. Of course, you would still need to test MyBaseClass itself separately.

Related

Should protected methods be unit-tested? How to avoid repetitive testing?

Using C#
I know this has been asked before and a lot of people will answer no, only test public methods, not implementation details. Others will say yes, if it has some important logic. Although you might then consider breaking it off into its own class.
One issue I haven't seen addressed is having to repeat testing public methods that call protected methods in inherited classes.
If I test the protected method in the base class, surely I don't have to retest it in base classes. Or should I copy and paste the tests to multiple classes?
You definitely should test protected methods. From a testing standpoint, a "protected" method still is part of the public interface, even though the "public" is limited to those classes that derive from your class. Because code that you do not control can reference those methods, you must ensure that they function as defined.
As for repetitive testing, I don't have a definitive answer. If given:
public class A
{
protected virtual void Foo() {}
}
public class B:A
{
}
The question is whether you write a test for B.Foo. On one hand I would say no, because B doesn't provide an explicit implementation of Foo, and so its behavior can't possibly be different than the behavior of A.Foo, and we can assume that you've already tested A.Foo.
On the other hand, A.Foo could depend on some other protected fields or properties that B could modify, or on a private callback that B provides in a constructor or initialization function. In that case, then you absolutely must test B.Foo because its behavior could be different than A.Foo, even though B doesn't override A.Foo.
Obviously, if B overrides Foo, then you have to write a test for B.Foo. But if B doesn't override A.Foo, then you have to use your judgement.
All that said, it's really no different from having to write tests for any class that derives from another. Consider deriving a class from TextWriter. Would you write explicit unit tests for all of the virtual functions defined by the TextWriter class? Or would you write tests only for those methods that you override, and those methods whose functionality might have changed as a side effect?
There is a lot of opinions on what should be Unit Tested and what should not.
My personal belief is that for every function you write, you should have written a unit test first to specify the desired behavior. You then write your code to make this test pass. This is applicable for private, public, protected and internal. If it is used it should be unit tested.
Believe me this makes your life easier in the long run because if you or another developer changes existing unit tested code then a change in behavior is a lot more likely to be caught.
In the real world though it usually ends up being code first then test. However they should still be written for all access levels.

How to structure unit tests when you want to test interactions of derived classes wih base class

I started organizing my unit tests in the way Phil Haack suggested here. My test classes have one nested class per public method under test. The nested classes are derived from the outer class in order to inherit its setup code.
I now have a case where I want to test a simple hierarchy of one abstract base class and two derived classes. I would like to test the interactions of each derived class with base class explicitly rather than testing the base class with some kind of mock derived class.
I've done this in the past using a base test fixture and one derived fixture per derived class where the derived fixtures have to implement a few template methods for the tests in the base fixture:
[TestFixture]
public abstract class BaseFixture
{
protected abstract MyBaseClassUnderTest GetTestInstance();
[Test]
public void SomeMethod_SomeCondition_SomeOutcome()
{
var sut = GetTestInstance();
//test base class behavior here
}
//More base class tests here
}
public class DerivedFixture : BaseFixture
{
protected override MyBaseClassUnderTest GetTestInstance()
{
return new DerivedInstance();
}
//Tests for derived class go here
}
Does anybody have an idea, how I can resolve this? Right now I can't see, how I can combine the two approaches, because of the different inheritance strategies (inheriting setup code from the outer class versus inheriting base class tests from base class fixture).
It's a really interesting problem, of course multiple inheritance isn't possible therefore I guess you need to find an alternative to one of the two inheritance strategies you are using.
Personal opinion is that you should keep the Haack method of organizing tests for consistency across the test suite, and look for an alternative to your approach for sharing tests through a class hierarchy. The closest concept I know to multiple inheritance is that of Mixins, and if you look at this answer to Is it Possible to Implement Mixins in C# it appears that mixins can be simulated using extension methods. I would go down this path - this blog post discusses possible strategies for creating mixins that can access data held in the class that uses them, which you would require I believe to be able to supply the derived class instance to your base class level tests (i.e. replacing GetTestInstance).

C# stubbing. Interface for every testable object?

I've seen multiple answers regarding 'how to stub your classes so you can control what happens within the SUT'.
They say one thing:
Create an interface and inject that interface using dependency injection and create a stub using that same interface that you then inject into the SUT.
However, what I've learned in my previous working places:
If you unit test, you test all classes/functionality.
Does that mean that for every class that has a specific function-layout you have to create an interface?
That would mean the amount of classes/files would just about be twice as many.
As seen in the example below, is this 'the way to go' or am I missing something in my unit testing process?
As a note:
I am using VS2012 Express. That means no 'Faker' framework. I am using the 'standard' VS2012 unit testing framework.
As a very, very simple example, which allows me to stub each interface passed down to a SUT.
IFoo.cs
public interface IFoo
{
string GetName();
}
Foo.cs
public class Foo : IFoo
{
public string GetName()
{
return "logic goes here";
}
}
IBar.cs:
public interface IBar : IFoo
{
IFoo GetFoo();
}
Bar.cs:
public class Bar : IBar
{
public string GetName()
{
return "logic goes here";
}
public IFoo GetFoo()
{
return null; // some instance of IFoo
}
}
IBaz.cs:
public interface IBaz
{
IBar GetBar();
}
Baz.cs:
public class Baz
{
public IBar GetBar()
{
return null; // some instance of IBar
}
}
In my opinion, you should not create interfaces just for the purpose of unit testing. If you start adding code abstractions to please the tools, then they are not helping you to be more productive. The code you write should ideally serve a specific business purpose/need - either directly, or indirectly by making the code base easier to maintain or evolve.
Interfaces sometimes do this, but certainly not always. I find that providing interfaces for components is usually a good thing, but try to avoid using interfaces for internal classes (that is, code only used inside of the given project, regardless of whether the types are declared public or not). This is because a component (as in, a set of classes working together to solve some specific problem) represents a larger concept (such as a logger or a scheduler), which is something that I may feasibly want to replace or stub out when testing.
The solution (hat tip to Robert for being first in the comments) is to use a mocking framework to generate a compatible substitution type at run-time. Mocking frameworks then allow you to verify that the class being tested interacted correctly with the substituted dummy. Moq is as mentioned a snazzy choice. Rhino.Mocks and NMock are two other popular frameworks. Typemock Isolator hooks into the profiler and is among the more powerful options (allows you to substitute even non-virtual private members), but is a commercial tool.
It's no good making up rules for how much you should unit test. It depends on what you're developing and what your goals are - if correctness always trumps time-to-market and cost is not a factor then unit testing everything is great. Most people are not so lucky and will have to compromise to achieve a reasonable level of test coverage. How much you should test may also depend on overall skill level of the team, expected lifetime and reuse of the code being written, etc.
Yes and no. In order to stub dependency you need some sort of abstraction, but that's in majority because of how mocking frameworks work (not all, naturally).
Consider simple example. You test class A that takes dependencies to classes B and C. For unit tests of A to work, you need to mock B and C - you'll need IB and IC (or base classes /w virtual members). Do you need IA? No, at least not for this test. And unless A becomes dependency to some other class, abstracting it behind interface/base class is not required.
Abstraction is great as it helps you build losely coupled code. You should abstract your dependencies. However, in practice some classes need not to be abstracted as they serve top-level/end-of-hierarchy/root roles and are not used elsewhere.
Maybe from a purist perspective that is the right way to go, but the really important thing is to make sure that external dependencies (e.g. database, network access, etc), anything that is computationally expensive/time consuming, and anything that isn't fully deterministic is abstracted away and easy to replace in your unit tests.
From a testing perspective, there is no need to make an interface for every class in your code. You make an interface to hide concrete execution of external dependencies behind a layer of abstraction. So instead of having a class that requires a direct HTTP connection mixed in with your logic, you would isolate the connection code to a class, have it implement an interface that is a member of your class, and inject a mock in place pf that interface. That way, you can test your logic in isolation, free of dependency, and the only "untested" code is boilerplate HTTP connection code that can be tested through other means.
I'd go the virtual method route. Creating interfaces for every class you need to test gets really burdensome, especially when you need tools like Resharper for the "go to implementation" every time you'd like to see the definition of a method. And there's the overhead of managing and modifying both files any time a method signature is changed or a new property or method is added.

c# practices for correct object oriented techniques

I have some c# code that has been working well for a while now.. and I have to say, whilst I understand the basics of OO principles, there is obviously more than one way to skin a cat (although I hate that phrase!).
So, I have a base abstract class that is acting as a basic data service class as follows (much simplified just for ease of reading):
public abstract class dataservice
{
public enum OutputType : int { XmlTOJson = 0, Xml = 1, Json=2 }
protected object SomeDBcall(string StoredProcedure)
{
// Just assume we are using SQLclient/DB access..
object SomeReturnObjValue = db.ExecuteScalar(cmd);
return SomeReturnObjValue;
{
}
.. so basically I might have a few basic DB retrieve/update/delete calls in the abstract class.. mainly as there are the basis of any DB operation I have in my app.
So now we have a class that implements the base class, say in my case a customer class:
public class Customer : dataservice
{
Public String CustomerDoSomething(string SomeDataEtc)
{
// Ok, so again for simplicity sake, we are going to use the base class to
// call a DB retrieve
object ReturningObj = SomeDBcall("my stored procedure");
return ReturningObj.ToString();
}
}
So I guess my question is this: Is the above method "ok" to use? considering a virtual method could be over-ridden if required, however in this case I only want the base class to use those methods which are protected as the means to call the DB operations.
Any clarity/guidance very appreciated!
Sure, it's "ok", though I see no reason for the base class to be abstract. abstract classes are great for implementing some common logic and leaving the rest up to derived classes to implement. However, you have no abstract/virtual methods, so I don't see the point here.
Perhaps you can let your abstract class be concrete and use it as some kind of helper class which handles the database related stuff you need. As far as the example code shows, there is no need to have multiple database accessing classes, just different parameters.
Overview
Many times, your "development itself will guide you".
Practical answer.
(1) You define a base class "dataservice", and from that class, several other classes will be based upon. You marked as "abstract", thats good. It's not mean to have variables by itself.
Some developers won't mark that class as "abstract", its not obligatory, but, its a not a bad idea, but, its a "good practice", to marked "abstract".
And, other methods will be added, used by the subclasses, maybe overriden, maybe not.
For know, those methods are protected, and anot mean to be used outside the object, but, by other methods. That's ok.
Maybe, later, a method may be required to be used outside the class, and may have to change to public.
(2) You add a subclass "Customer" that is a descendant from "DataService" You add a method that has to be used outside the class, and marked as "public", good.
It's only meant to be used by this class, not the parent class. So, no "virtual" or "override" required. Good.
(3) Your example its very simple. Most things you did, seems fine to me.
Eventually, when you add more code, things may change, example a method in the base class that was private may become public, or you may "rename" or "refactor" a method, like "dosomething", and found out that its better to be in the base class, or maybe not.
Summary
There are other answers, that mention, rules, or concepts. Seems to me that they are OK, but, skip the fact that you are learning to use O.O.P. better. Some people just try to "eat the cake in one wingle big bite", and that's not a good idea.
P.D. "can ur skin ur rabbit", sounds better to me.
Cheers.
You might want to look to the Template pattern to define the interface in the base (abstract or not) class with defined protected virtual hooks that can be overridden in the concrete subclasses. As mentioned by another poster, if you just intend to add DB services to each of your domain areas you might look to encapsulate the basic database service methods into a helper class rather than deriving from the database service.
Thanks #jgauffin for questioning my LSP violation statement. It was not correct and has been removed. There are lots of cases where extending the public interface of the base class by subclasses is warranted. Of course, by doing that one needs to be careful that you have an instance of a Y and not an X or a Z when performing a Y-specific operation A(), assuming that both Y and Z derive from X where Y adds the new public method A() and Z does not.
An example of the Template pattern in the OP's context would allow better encapsulation of custom functionality within subclasses without extending the public interface. However, this only works if there is not external influence exerted on the subclass instance, such as the OP's SomeDataEtc parameter. This works best when the instance is immutable.
public abstract class DataService
{
protected object myWidget = new Widget();
public object SomeDataBaseCall(string storedProcedure)
{
DoSomeCustomThing();
//do db stuff
object SomeReturnObjValue = db.ExecuteScalar(storedProcedure);
return SomeReturnObjValue;
}
protected void DoSomeCustomThing() {}
}
public class Customer : DataService
{
override protected void DoSomeCustomThing()
{
// do your custom thing here
}
}
Additionally, in the OP's example, it would seem prudent to use delegation within the derived class's new public method to call the base class's SomeDBCall method to execute the stored procedure. If you are redundantly coding the db access methods then there is no benefit to the proposed inheritance.
As was also mentioned elsewhere, you might be better off altogether by using composition rather than inheritance for the data service functionality.
No. Guess your following data access object pattern (DAO). Either way your Customer is not your data access class. It uses a class for data access. What I mean is that your DAO should favor composition over inheritance.
Something like:
public class Customer : IDataAccessObject
{
public Customer()
{
_dataAccess = new DataAccess();
}
public string CustomerDoSomething(string SomeDataEtc)
{
object ReturningObj = _dataAccess.SomeDBcall("my stored procedure");
return ReturningObj.ToString();
}
}
Why? Your objects get's a single responsibility which means that it's easier to extend and refactor them.
You can read up about SOLID which is some fundamental programming principles.
Since you are a .NET developer I also recommend that you embrace the naming guidelines.

NUnit - How to test all classes that implement a particular interface

If I have interface IFoo, and have several classes that implement it, what is the best/most elegant/cleverest way to test all those classes against the interface?
I'd like to reduce test code duplication, but still 'stay true' to the principles of Unit testing.
What would you consider best practice? I'm using NUnit, but I suppose examples from any Unit testing framework would be valid
If you have classes implement any one interface then they all need to implement the methods in that interface. In order to test these classes you need to create a unit test class for each of the classes.
Lets go with a smarter route instead; if your goal is to avoid code and test code duplication you might want to create an abstract class instead that handles the recurring code.
E.g. you have the following interface:
public interface IFoo {
public void CommonCode();
public void SpecificCode();
}
You might want to create an abstract class:
public abstract class AbstractFoo : IFoo {
public void CommonCode() {
SpecificCode();
}
public abstract void SpecificCode();
}
Testing that is easy; implement the abstract class in the test class either as an inner class:
[TestFixture]
public void TestClass {
private class TestFoo : AbstractFoo {
boolean hasCalledSpecificCode = false;
public void SpecificCode() {
hasCalledSpecificCode = true;
}
}
[Test]
public void testCommonCallsSpecificCode() {
TestFoo fooFighter = new TestFoo();
fooFighter.CommonCode();
Assert.That(fooFighter.hasCalledSpecificCode, Is.True());
}
}
...or let the test class extend the abstract class itself if that fits your fancy.
[TestFixture]
public void TestClass : AbstractFoo {
boolean hasCalledSpecificCode;
public void specificCode() {
hasCalledSpecificCode = true;
}
[Test]
public void testCommonCallsSpecificCode() {
AbstractFoo fooFighter = this;
hasCalledSpecificCode = false;
fooFighter.CommonCode();
Assert.That(fooFighter.hasCalledSpecificCode, Is.True());
}
}
Having an abstract class take care of common code that an interface implies gives a much cleaner code design.
I hope this makes sense to you.
As a side note, this is a common design pattern called the Template Method pattern. In the above example, the template method is the CommonCode method and SpecificCode is called a stub or a hook. The idea is that anyone can extend behavior without the need to know the behind the scenes stuff.
A lot of frameworks rely on this behavioral pattern, e.g. ASP.NET where you have to implement the hooks in a page or a user controls such as the generated Page_Load method which is called by the Load event, the template method calls the hooks behind the scenes. There are a lot more examples of this. Basically anything that you have to implement that is using the words "load", "init", or "render" is called by a template method.
I disagree with Jon Limjap when he says,
It is not a contract on either a.) how the method should be implemented and b.) what that method should be doing exactly (it only guarantees the return type), the two reasons that I glean would be your motive in wanting this kind of test.
There could be many parts of the contract not specified in the return type. A language-agnostic example:
public interface List {
// adds o and returns the list
public List add(Object o);
// removed the first occurrence of o and returns the list
public List remove(Object o);
}
Your unit tests on LinkedList, ArrayList, CircularlyLinkedList, and all the others should test not only that the lists themselves are returned, but also that they have been properly modified.
There was an earlier question on design-by-contract, which can help point you in the right direction on one way of DRYing up these tests.
If you don't want the overhead of contracts, I recommend test rigs, along the lines of what Spoike recommended:
abstract class BaseListTest {
abstract public List newListInstance();
public void testAddToList() {
// do some adding tests
}
public void testRemoveFromList() {
// do some removing tests
}
}
class ArrayListTest < BaseListTest {
List newListInstance() { new ArrayList(); }
public void arrayListSpecificTest1() {
// test something about ArrayLists beyond the List requirements
}
}
I don't think this is best practice.
The simple truth is that an interface is nothing more than a contract that a method is implemented. It is not a contract on either a.) how the method should be implemented and b.) what that method should be doing exactly (it only guarantees the return type), the two reasons that I glean would be your motive in wanting this kind of test.
If you really want to be in control of your method implementation, you have the option of:
Implementing it as a method in an abstract class, and inherit from that. You will still need to inherit it into a concrete class, but you are sure that unless it is explicitly overriden that method will do that correct thing.
In .NET 3.5/C# 3.0, implementing the method as an extension method referencing to the Interface
Example:
public static ReturnType MethodName (this IMyinterface myImplementation, SomeObject someParameter)
{
//method body goes here
}
Any implementation properly referencing to that extension method will emit precisely that extension method so you only need to test it once.
How about a hierarchy of [TestFixture]s classes? Put the common test code in the base test class and inherit it into child test classes..
When testing an interface or base class contract, I prefer to let the test framework automatically take care of finding all of the implementers. This lets you concentrate on the interface under test and be reasonably sure that all implementations will be tested, without having to do a lot of manual implementation.
For xUnit.net, I created a Type Resolver library to search for all implementations of a particular type (the xUnit.net extensions are just a thin wrapper over the Type Resolver functionality, so it can be adapted for use in other frameworks).
In MbUnit, you can use a CombinatorialTest with UsingImplementations attributes on the parameters.
For other frameworks, the base class pattern Spoike mentioned can be useful.
Beyond testing the basics of the interface, you should also test that each individual implementation follows its particular requirements.
I don't use NUnit but I have tested C++ interfaces. I would first test a TestFoo class which is a basic implementation of it to make sure the generic stuff works. Then you just need to test the stuff that is unique to each interface.

Categories

Resources