Internals, InternalsVisibleTo and testing shared behavior - c#

We have a shared basic interface public interface IOperation {...} and lots (tens, soon 100+) different objects that implement IOperation.
We also have tests for all those implementations, all inheriting from base classes called TestOperationCommon that are templated with the actual operations class and types for a Create method to new such an operation. We have implementations for TestOperationCommon with one up to five template parameters (which is enough for all operations).
Now, recently it was decided to make all operation implementations internal and only have IOperation public, which seems like a good idea as those ops are implementation details. And with [InternalsVisibleTo(...)] testing seemed solved, too.
However, now I see that we cannot use our test structure anymore, as the generic parameters to the public test class are now internal (at least the actual class under test is), which leads to
Inconsistent Accessibility .... less accessible than ...
errors. The code below, a public test class cannot inherit from TestOperationCommon with a generic parameter T that is internal. But duplicating all those shared-behavior tests into the specific tests also seems like a bad idea.
Is there a way to get the vstest framework (VS2013+) to test [TestClass]es that are internal?
Or is there another way we can keep the shared tests without having to duplicate lots of code?
Or are we doing it wrong (making those 'implementation detail-classes` internal)?
Code example as request in comment:
public interface IOperation { ... }
internal class SomeOperation : IOperation
{
public SomeOperation(A a, B b, C c) {...}
}
public abstract TestOperationCommon<T, A, B, C>
where T : IOperation
where ...
{
protected abstract T Create(A a, B b, C c);
[TestMethod]
public void TestCommonOperationBehavior()
{
var op = Create(Mock.Of<A>(), Mock.Of<B>(), Mock.Of<C>);
...
}
}
[TestClass]
public class TestSomeOperation : TestOperationCommon<SomeOperation, ...>
{
[TestMethod]
public void TestSpecificSomeOperationStuff() {}
}

Could you creating a test wrapper class?
Something like:
[TestClass]
public class AnnoyingTestSomeOperationWrapper
{
[TestMethod]
public void TestSpecificSomeOperationStuff()
{
new TestSomeOperation().TestSpecificSomeOperationStuff()
}
}
internal class TestSomeOperation : TestOperationCommon<SomeOperation, ...>
{
public void TestSpecificSomeOperationStuff() {}
}

Related

Grouping Unity NUnit tests?

I want to group tests like this:
To get this screenshot I used TestCases, but they don't really apply to my needs.
Obviously I don't want this:
[TestCase(TestName = "ShouldDoSomething")]
[TestCase(TestName = "ShouldDoSomethingElse")]
public void OnJoinRoom()
{ ... }
I want something like this:
[TestGroup("OnJoinRoom")]
public void ShouldDoSomething()
{ ... } 
[TestGroup("OnJoinRoom")]
public void ShouldDoSomethingElse()
{ ... } 
I don't think using subclasses is an option, as the tests are depending on a SetUp method used in the TestFixture class.
In NUnit, TestFixtures are used to group tests as well as to provide a common setup. The normal way to provide a common setup across multiple TestFixtures is to have a common base class like
public class CommonBase
{
[SetUp]
public void CommonSetUp() { }
}
[TestFixture]
public class OnJoinRoom : CommonBase { }
[TestFixture]
public class OnLeaveRoom : CommonBase { }
Notes:
Put all your tests in the derived classes
TestFixture attribute is optional, of course, but do not put it on the base class.
Base class may be abstract if you like.

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"));
}

Share a private implementation between two classes in C#

I'm looking for a way to share the implementation of two classes without exposing any details of that sharing. I was hoping to create this basic class structure:
public interface MyInterface
class MyCommonImpl : MyInterface
public class MyImplA : MyCommonImpl
public class MyImplB : MyCommonImpl
MyCommonImpl implements the functions of MyInterface and has one abstract function provided in MyImplA and MyImplB. A user of MyImplA should not know about MyCommonImpl in any fashion, it's just an implentation detail.
I've considered doing manual composition, but this involves copying a lot of code to forward the functions. It's also problematic since there are events implemented in MyCommonImpl, and one of their parameters is a sender. This requires putting a proxy handler and partially rewriting events. Basically composition would require more code than simply copy-pasting the entire MyCommonImpl.
How can I do this without having to duplicate a lot of code?
You can move the interfaces and implementations to another assembly and mark them internal which will hide the abstract function of MyCommonImpl. Taking it further, you could explicitly implement the interfaces inside that assembly to completely hide their methods from callers leaving only those methods declared public on MyImplA visible.
The internal casts for the explicit implementation are a bit nasty though...
In a separate assembly:
namespace Private
{
internal interface IMyInterface
{
void InterfaceMethod();
}
public abstract class MyCommonImpl : IMyInterface
{
internal MyCommonImpl()
{
// internal ctor to stop callers constructing
}
void IMyInterface.InterfaceMethod()
{
Console.WriteLine("InterfaceMethod");
}
internal abstract void CommonAbstract();
}
public class MyImplA : MyCommonImpl
{
internal override void CommonAbstract()
{
((IMyInterface)this).InterfaceMethod();
Console.WriteLine("CommonAbstract");
}
public void ImplAMethod()
{
CommonAbstract();
Console.WriteLine("ImplAMethod");
}
}
}

TDD and inheritance

I am working on my first project using TDD and have hit a bit of a brick wall when it comes to inheritance.
For example if I have something like this
public interface IComponent
{
void MethodA();
void MethodB();
}
public class Component : IComponent
{
public virtual void MethodA()
{
// Do something
}
public virtual void MethodB()
{
// Do something
}
}
public class ExtendedComponent : Component
{
public override void MethodA()
{
base.MethodA();
// Do something else
}
}
then I cannot test ExtendedComponent in isolation because it depends on Component.
However, if I use composition to create ExtendedComponent like this
public class ExtendedComponent : IComponent
{
private readonly IComponent _component;
public ComponentB(IComponent component)
{
_component = component;
}
public virtual void MethodA()
{
_component.MethodA();
// Do something else
}
public virtual void MethodB()
{
_component.MethodB();
}
}
I can now test ExtendedComponent in isolation by mocking the wrapped IComponent.
The downside of this approach is that if I want to add new methods to IComponent then I have to add the new methods to Component and ExtendedComponent and any other implementations of which there could be many. Using inheritance I could just add the new method to the base Component and it wouldn't break anything else.
I really want to be able to test cleanly so am favouring the composition route but I am concerned that being able to unit test is not a valid reason to always use composition over inheritance. Also adding functionality at the base level will require the creation of lots of tedious delegating methods.
I'd really appreciate some advice on how other people have approached this kind of problem
your approach using composition is in all practicallity how most compilers implement inheritance so you gain nothing but pay a heavy cost (a lot of boilerplate code). So stick to the inheritance when there's a is-a relationship and composition when there is a has-a relation ship (those of course are neither gold nor the sole rules)
You don't need to worry about testing the extended component 'in isolation' because it does not 'depend' on component it IS a component (at least it is in the way you coded it).
All the tests you originally wrote for the component class are still fine and test all the unchanged behaviour in the extended class as well. All you need to do is write new tests that test the added functionality in the extended component.
public class ComponentTests{
[Fact]
public void MethodADoesSomething(){
Assert.xxx(new Component().MethodA());//Tests the component class
}
[Fact]
public void MethodBDoesSomething(){
Assert.xxx(new Component().MethodB());//Tests the component class
}
}
public class ExtendedComponentTests{
[Fact]
public void MethodADoesSomething(){
Assert.xxx(new ExtendedComponent().MethodA());//Tests the extended component class
}
}
You can see from above that MethodA functionality is tested for both the component AND the extended component. While the new functionality is only tested for the ExtendedComponent.
The key idea here is that one can have inheritance at unit test side too.
I use following approach in this scenario. I'll have a parallel inheritance hierarchy of unit test cases. e.g.
[TestClass]
public abstract class IComponentTest
{
[TestMethod]
public void TestMethodA()
{
// Interface level expectations.
}
[TestMethod]
public void TestMethodB()
{
// Interface level expectations.
}
}
[TestClass]
public class ComponentTest : IComponentTest
{
[TestMethod]
public void TestMethodACustom()
{
// Test Component specific test, not general test
}
[TestMethod]
public void TestMethodBCustom()
{
// Test Component specific test, not general test
}
}
[TestClass]
public class ExtendedComponent : ComponentTest
{
public void TestMethodACustom2()
{
// Test Component specific test, not general test
}
}
Each abstract test class or concrete class deals with expectations at it's own level. Thus extensible and maintainable.
You are correct - using composition over inheritance where it is not appropriate is not the way to go. Based on the information that you have provided here, it is not clear which is better. Ask yourself which one is more appropriate in this situation. By using inheritance, you get polymorphism and virtualization of methods. If you use composition, you are effectively separating your "front-end" logic from the isolated "back-end" logic -- this approach is easier in that changing the underlying component does not have a ripple effect on the rest of the code as inheritance often does.
All in all, this should not affect how you test your code. There are many frameworks for testing available, but this should not affect which design pattern you choose.

Exposing different interfaces from single class

We are trying to build some kind of a layer above the DAL in order to expose an interface of a certain repository methods using generics.
For example:
public interface A
{
void Do_A();
}
public interface B
{
void Do_B();
}
public void Main()
{
Exposer<A>.Do_A();
Exposer<B>.Do_B();
}
Is it possible to do that ?
Tecnically, that isn't a "single class", since Exposer<A> is a different Type to Exposer<B>; however, ultimately, this doesn't look much different to most IoC/DI containers... if this was, say, StructureMap (purely for an example), you might consider:
container.GetInstance<A>().Do_A();
container.GetInstance<B>().Do_B();
you would, of course, need to configure the container to know where the concrete A and B implementations are coming from! Which for StructureMap is shown here, but there are plenty to choose from.
If you mean directly, then: no. You cannot have:
class Exposer<T> : T {...} // non-working code to implement the interface T
You can, however, have some class:
class Exposer : A, B {...}
and just cast:
A a = Exposer;
a.Do_A();
B b = Exposer;
b.Do_B();
A type Foo<T> cannot implement (or extend) the actual T, as T is unknown at compile time. What you could do is expose a T as a property, and invoke methods on it. However, as Ondrej wrote, the question may be a little unclear.
Are you describing IoC when you write?
Exposer<A>.Do_A();
Your Exposer class makes me think to StructureMap API:
ObjectFactory.GetInstance<T>().Do_A();
If you want to get rid of the keyword new and get in a generic way an instance for a specified interface, take a look to this article or check StructureMap
To choose which interface implementation you want when consuming a given class, you don't use generics, you just cast the class to the interface:
public interface A
{
void Do_A();
}
public interface B
{
void Do_B();
}
public class Exposer : A, B
{
public void Do_A() { ; }
public void Do_B() { ; }
}
public void Main()
{
// the casts are redundant here,
// because the interface implementation
// is implicit
((A)Exposer).Do_A();
((B)Exposer).Do_B();
}
If you want to exclude members that are not implementations of members of the given interface, use explicit implementation:
public class Exposer : A, B
{
void A.Do_A() { ; }
void B.Do_B() { ; }
}
public void Main()
{
// the casts are now required;
// otherwise, you'll get a compiler error
// telling you that the method is inaccessible
((A)Exposer).Do_A();
((B)Exposer).Do_B();
}

Categories

Resources