C# unit testing question - c#

Does someone if the following code (idea, actually) is possible using xunit:
public class RepositoryTester {
private IRepository repository;
public RepositoryTester(IRepository repository) {
this.repository = repository;
)
[Fact] // Analogue of [Test] in other test packages.
void CanDoWhatever() {
// Test code
}
}
Now, if I attempt to run all unit test, it would fail as long as xunit attempts to create the object RepositoryTester by calling new RepositoryTester() (it invokes the constructor without parameters).
What I want to do can be equivalently expressed this way:
var tester1 = new RepositoryTester(new SQLRepository(...));
var tester2 = new RepositoryTester(new InMemoryRepository(...));
tester1. RUN_ALL_TESTS();
tester2. RUN_ALL_TESTS();
Does someone know if the following behavior is possible? (I really wish to use the same test package for every testable repository through it's interface).
Thank you

You can make RepositoryTester abstract, and have a derived class for each type of repository that creates an appropriate IRepository in a parameter-less constructor. The inherited test methods will be run for each concrete child class.

Related

Unable to return an interface in mocked method when it should be a internal sealed class

We are creating unit tests in XUnit for one of our projects our ASP.NET application. In the project, we are trying to mock out a particular third party client we don't have access to the source code and does not provide an interface (just a client object we can create). To fix this, we wrote a wrapper class and an interface to that class so we can mock out the functionality we need for that client. This part is all good.
One of the methods we created in the wrapper class and interface was a GetInnerChannel method to get a property from the client (which we want to mock out). However, that method returns an Interface of IClientChannel from System.ServiceModel.
public IClientChannel GetInnerChannel()
{
return client.InnerChannel;
}
It seems harmless, but, in our mock setup, we are unable to create a fake IClientChannel object that is useful for the method we are testing. Here is our unit test code for clarification:
client.Setup(i => i.GetInnerChannel()).Returns(GetClientChannel());
In the Returns call, you will see we are returning a method return which we currently set to null for now. This is because we cannot instantiate an interface. When I dived into debugging, I found that the object that is being sent back in place of the interface during normal operation is a System.Runtime.Remoting.Proxies.__TransparentProxy object. A little investigation into the __TransparentProxy class is that it is an internal sealed class (which means we cannot instantiate that in our unit test code).
Unfortunately, the method we are testing is using the InnerChannel in this way:
public List<EquifaxQuestion> GetEquifaxQuestions(User basicUserInfo, IEnumerable<AddressViewModel> Addresses)
{
try
{
InitialResponse response;
using (new OperationContextScope(client.GetInnerChannel()))
{
OperationContext.Current.OutgoingMessageHeaders.Add(
new EquifaxSecurityHeader(appID, username, password));
response = client.SubmitInitialInteraction(GenerateInitialRequest(basicUserInfo, Addresses));
}
Which I don't if we can replace the GetInnerChannel call and thus we require a mock of it to just get through the unit test since we must mock out our client.
Is there another way I can return a value or object that is useful for GetInnerChannel()? Am I missing a step in my mock setups? Or is Moq and other mocking frameworks incapable to do what I need to do? Or is the method I am trying unit test against unable to be unit tested? Thank you in advance.
Basically the solution for this was a lot of wrappers and interfaces to work in WCF. It is quite lengthy, but this blog post does a better job. https://weblogs.asp.net/cibrax/unit-tests-for-wcf
In short, if you have static, sealed, or other third party class you can't mock, wrap it in a simple task with all public methods written in them with them calling your third party class's method and then create an interface for the wrapper. In your unit tests, use the interface and in your normal code, use your wrapper class.
This is possible without having to write any more wrappers. It is important to understand the principle of indirection that gets introduced by adding an interface. Every interface added is an opportunity to isolate the abstraction and make it look and feel different.
I have attached the important snippets below, due to expected brevity I am not attaching entire solution.
Quick explaination of classes and usage hierarchy -
1. IInnerChannel is the interface exposed by the third party library.
2. IClientChannelWrapper is the wrapper class created in order to hide inner interface from calling clients.
3. ClassUsingChannelWrapper is the class that invokes this logic and in our unit test its method is going to be our sut (subject under test).
Code goes as below -
The IInnerChannel interface declaration-
public interface IInnerChannel
{
string TheInnerChannelMethod();
}
The InnerChannel implementation (probably in the third party library in your case)-
public class InnerChannelImplementation : IInnerChannel
{
public InnerChannelImplementation()
{
}
public string TheInnerChannelMethod()
{
var result = "This is coming from innser channel.";
Console.WriteLine(result);
return result;
}
}
The wrapper created by you around the inner channel -
public interface IClientChannelWrapper
{
void DoSomething();
IInnerChannel GetTheInnerChannelMethod();
}
The wrapper interface's implementation -
public class ClientChannelWrapperImplementation : IClientChannelWrapper
{
public ClientChannelWrapperImplementation()
{
}
public void DoSomething()
{
Console.WriteLine("The DoSomething Method!");
}
public IInnerChannel GetTheInnerChannelMethod()
{
InnerChannelImplementation imp = new InnerChannelImplementation();
return imp;
}
}
The class that calls your wrapper's implementation. This class is going to be your SUT when implementing unit tests -
public class ClassUsingChannelWrapper
{
IClientChannelWrapper _wrapper;
public ClassUsingChannelWrapper(IClientChannelWrapper wrapper)
{
_wrapper = wrapper;
}
public void TheClientChannelConsumerMethod()
{
IInnerChannel theChannel = _wrapper.GetTheInnerChannelMethod();
var result = theChannel.TheInnerChannelMethod();
Console.WriteLine(result);
}
}
Finally, the unit test with mocks mimicking behaviour of both interfaces. Notice how mocked client channel wrapper is returning mocked internal channel object which returns pre-programmed value.
public class UnitTest1
{
[Fact]
public void Test1()
{
//Arrange
Mock<IInnerChannel> innerChannelMock = new Mock<IInnerChannel>();
innerChannelMock.Setup(i => i.TheInnerChannelMethod()).Returns("This
is a test from mocked object.");
Mock<InterfaceUt.IClientChannelWrapper> mockClientWrapper = new
Mock<IClientChannelWrapper>();
mockClientWrapper.Setup(m =>
m.GetTheInnerChannelMethod()).Returns(innerChannelMock.Object);
//Act
ClassUsingChannelWrapper sut = new
ClassUsingChannelWrapper(mockClientWrapper.Object);
sut.TheClientChannelConsumerMethod();
//Assert
innerChannelMock.Verify();
mockClientWrapper.Verify();
}
}
Running this unit test prints
"This is a test from mocked object."
Essentially, your unit test is targeting only the client code that attempts to use your interface behaviour. This does not test the implementation of your wrapper. If you want to achieve that you will have to create a new instance of wrapper class instead of mock object and feed it with inner channel's mock object.

NUnit TestFixture with no-arg constructors

How do you get around the scenario where the TestFixture you are trying to define needs to reference types that do not have a no-arg constructor?
I'm trying to test an interface that has multiple implementations. From the NUnit documentation it showed how this could be setup with generics like this (where I can define multiple implementation types):
[TestFixture(typeof(Impl1MyInterface))]
[TestFixture(typeof(Impl2MyInterface))]
[TestFixture(typeof(Impl3MyInterface))]
public class TesterOfIMyInterface<T> where T : IMyInterface, new() {
public IMyInterface _impl;
[SetUp]
public void CreateIMyInterfaceImpl() {
_impl = new T();
}
}
The problem arises because Impl1MyInterface, Impl2MyInterface, etc do not have no-arg constructors so when NUnit tries to discover the available test cases I get this error (and the tests do not show up in VS):
Exception System.ArgumentException, Exception thrown discovering tests
in XYZ.dll
Is there a way to work around this? It doesn't make sense to define no-arg constructors because my code needs those values to work.
Instead of using new T() to instantiate your objects, you could use a dependency injection container to instantiate them for you. Here's an example using Microsoft's Unity:
[SetUp]
public void CreateIMyInterfaceImpl() {
var container = new UnityContainer();
// Register the Types that implement the interfaces needed by
// the Type we're testing.
// Ideally for Unit Tests these should be Test Doubles.
container.RegisterType<IDependencyOne, DependencyOneStub>();
container.RegisterType<IDependencyTwo, DependencyTwoMock>();
// Have Unity create an instance of T for us, using all
// the required dependencies we just registered
_impl = container.Resolve<T>();
}
As #Steve Lillis has said in his answer, you need to stop using new T(). When you do this, you don't need to use the new constraint on your generic. One option would be to use an IOC container, like Castle Windsor / Unity as Steve suggested to resolve the dependencies in your Setup.
You haven't said what parameters your implementation's constructors take, but if they're all the same, then an alternate would be to use Activator.CreateInstance instead. So, if your constructors all took an integer and a string, your code would look like this:
[TestFixture(typeof(Impl1MyInterface))]
[TestFixture(typeof(Impl2MyInterface))]
[TestFixture(typeof(Impl3MyInterface))]
public class TesterOfIMyInterface<T> where T : IMyInterface {
public IMyInterface _impl;
[SetUp]
public void CreateIMyInterfaceImpl() {
int someInt1 = 5;
string someString = "some value";
_impl = (T)Activator.CreateInstance(typeof(T), new object[] { someInt1, someString });
}
}

Is it ok to mock parts of the class I am testing?

I am currently writing unit tests for a class that formats values based on parameters found in a big xml file.
The class I am testing receives another class in its constructor that provides functionality to parse and read the xml files. I think it is bad style to give the tested class a concrete instance of the xml reading class, because I believe doing so would result in testing the xml reading class every time I want to - in fact - test the formatting functions of the main class. All unit tests in the formatting class would fail if there was a problem in the xml reading class, which is clearly not the formatting class' fault.
So how should I proceed?
Obviously I would just create a mock of the xml reading class and pass that as an argument to the constructor. However the formatting class would use this instance to create about 5 private instances of other classes.
Because I don't know what these classes want to do (and honestly these tests should not care) I would like to mock away these private fields of the class I am testing.
Is that even ok to do? How would I do that using Moq?
-edit-
see the following example:
public class FormatterCore : IFormatterInterfaceIWantToTest
{
public FormatterCore(IConfigService service)
{
this.something = new SomeStuffA(service);
this.somethingThatINeed = new SomethingUserfull(service);
this.somethingElse = new SomeOtherStuff(service);
this.somethingTotallyDifferent = new SomeReallyUselessStuff(service);
//...
}
public T Format<T>(object input, string id)
{
// implementation of the interface I want to test
}
}
In my example I want to test the method Format<T>() of the interface. To create an instance of the Formatter class, I'd need to pass an instance of a IConfigService implementation (which is expensive and cumbersome, because it would require different xml files and takes a while). My problem here is that I don't want to create an instance of the configService for every unit test because this would mean that I'd test the configService itself with every test in the FormatterCore unit.
In order to test FormatterCore you should not create an instance of a IConfigService implementation. You have to create and set up a mock object of IConfigService.
[TestClass]
public class FormatterCoreTest
{
Mock<IConfigService> сonfigServiceMock;
[TestInitialize]
public void Init()
{
сonfigServiceMock = new Mock<IConfigService>();
}
[TestMethod]
public void Format()
{
// arrange
var input = /* input value */;
var id = /* id value */;
var сonfigServiceMock
.Setup(services => services.YourMethodToMock())
.Returnes(/* expected result or behaviour */);
// act
var target = new FormatterCore(сonfigServiceMock.Object);
var result = target.Format</* AnyType */>(input, id);
// assert
/* Your asserts */
result.Should().Be(/* expectred result */);
Assert.AreEqual /* expectred result */, result);
}
}
Are types SomeStuffA, SomethingUserfull, SomeOtherStuff and SomeReallyUselessStuff nested and can't be tested or public and it is possible?
If it is possible to test types SomeStuffA, SomethingUserfull, SomeOtherStuff and SomeReallyUselessStuff then it is better to inject their instances into constructor of FormatterCore instead of creating them in the constructor.
public class FormatterCore : IFormatterInterfaceIWantToTest
{
ISomeStuffA something;
ISomethingUserfull somethingThatINeed;
ISomeOtherStuff somethingElse;
ISomeReallyUselessStuff somethingTotallyDifferent;
public FormatterCore(
ISomeStuffA someStuffA,
ISomethingUserfull somethingUserfull,
ISomeOtherStuff someOtherStuff,
ISomeReallyUselessStuff someReallyUselessStuff
)
{
this.something = someStuffA;
this.somethingThatINeed = somethingUserfull;
this.somethingElse = someOtherStuff;
this.somethingTotallyDifferent = someReallyUselessStuff;
//...
}
public T Format<T>(object input, string id)
{
// implementation of the interface I want to test
}
}
Let your IoC be responsible for instance creation.
It will be needed to create and setup mocks for all dependencies in every test.
As you can't access the private variables of the XML formatting class (other than hacking into the class by reflection), and you can't be certain of when the other classes are created, I don't think you can mock them in the way you'd like to. Having to hack into a class to access private variables or methods for testing is a code smell - it means you have hidden testable functionality that should be exposed.
So, to expose that functionality, it seems like your best course of action would be to inject factories that the XML formatting class uses to create these other classes. Your XML reader/parser mock would be passed to the Create methods, and you would return appropriate mocks of those classes for the XML formatting class to use.
Alternatively, you could treat the XML formatting class as you would in an integration test - accept that other classes will be created with your XML reader/parser mock as a parameter, and set up that mock to expect calls from them as well.

How to mock windsor container in order to test registration

For educational purposes, how should I setup a mock of IWindsorContainer, so I can unit test performed registration?
Suppose I have a method like this:
public void MakeRegistration<S, T>(IWindsorContainer container)
where S : class
where T : class, S
{
container.Register(Component.For<S>().ImplementedBy<T>().LifeStyle.Transient);
}
I would like to write a unit test for it, using Moq:
var container = new Mock<IWindsorContainer>(MockBehavior.Strict);
container.Setup(c => c.Register(
Component.For<IFoo>()
.ImplementedBy<Foo>()
.LifeStyle.Transient));
var registrar = new MyRegistrar();
registrar.MakeRegistration<IFoo, Foo>(container.Object);
The above fails, as expected, but I'm curious how to properly test it.
I could use real container instead of a mock, and verify that it resolves 2 different instances of the class, but I consider it not "pure" unit test, as it actually relies on the workings of external code (windsor container itself).
As I said, this is theoretical, so if it's needed or not is out of the scope of the question.
You just need an assertion that the implementation Foo was registered against the service IFoo that would be the pure test (Example using NSubstitute as I have not used moq for some time).
[ Test ]
public void Should_register_implemenation_of_Foo_for_service_IFoo()
{
var container = Substitute.For<IWindsorContainer>();
container.Register( Component.For<IFoo>().ImplementedBy<Foo>() );
container.Received().Register( Arg.Is<IRegistration[]>(x => Test(x) ));
}
private bool Test(IRegistration[] registrations)
{
var fooRegistration = (ComponentRegistration<IFoo>) registrations[ 0 ];
return fooRegistration.Implementation == typeof(Foo);
}
public interface IFoo {}
public class Foo : IFoo {}
I know you have said that the question theoretical but it is important to ask the following question so that those new to TDD assume that you must do things this way.
Should a test dictate how a component achieves it's goal or should it just test that a component actually achieves it's goal?
IMO I feel that there is more value in writing an integration test that shows that the wire up is correct over making sure that certain methods are called on dependencies.

NUnit Mocking not working for Singleton Method

Bear with me, I'm new to NUnit. I come from the land of Rails, so some of this is new to me.
I have a line of code that looks like this:
var code = WebSiteConfiguration.Instance.getCodeByCodeNameAndType("CATALOG_Brands_MinQty", item.Catalog);
I'm trying to mock it, like this (assume code is already initialized):
var _websiteConfigurationMock = new DynamicMock(typeof(WebSiteConfiguration));
_websiteConfigurationMock.ExpectAndReturn("getCodeByCodeNameAndType", code);
When I debug the test, getCodeByCodeNameAndType is returning null, instead of the expected code. What am I doing wrong?
NUnit version: 2.2.8
I'm sorry, but I've never used NUnit.Mocks - but I do have some experience with NMock and Moq [which, by the way, I highly recommend]. Typically, you use a mocking library to generate proxies for Interface definitions, and I presume NUnit.Mocks operates the same way.
Therefore, if you would like to mock your singleton, you will likely have to do the following,
a. Create an interface, say
// All methods you would like to mock from this class, should
// be members of this interface
public interface IWebSiteConfiguration
{
// Should match signature of method you are mocking
CodeType getCodeByCodeNameAndType (
string codeString,
CatalogType catalogType);
}
b. "Implement" interface
// You've already written the method, interface matches signature,
// should be as easy as slapping interface on class declaration
public class WebSiteConfiguration : IWebSiteConfiguration { }
c. Consume interface
alright, so step c. is where most of your work will be. Logically, if you are mocking your singleton, you are actually unit testing the consumer [which you have left out of your sample]. For c. simply add a parameter to the consumer's ctor, or add a publicly accessible property of Type 'IWebSiteConfiguration', and then internally, reference the instance member and invoke your methods against this new interface. Consider this,
was
public class MyClass
{
public MyClass () { }
public void DoSomething ()
{
// bad singleton! bad boy! static references are bad! you
// can't change them! convenient but bad!
code = WebSiteConfiguration.Instance.getCodeByCodeNameAndType (
"some.string",
someCatalog)
}
}
becomes
public class MyClass
{
private readonly IWebSiteConfiguration _config = null;
// just so you don't break any other code, you can default
// to your static singleton on a default ctor
public MyClass () : this (WebSiteConfiguration.Instance) { }
// new constructor permits you to swap in any implementation
// including your mock!
public MyClass (IWebSiteConfiguration config)
{
_config = config;
}
public void DoSomething ()
{
// huzzah!
code = _config.getCodeByCodeNameAndType ("some.string", someCatalog)
}
}
In your unit test, create the mock, pass a reference of the mock to the consumer, and test the consumer.
[Test]
public void Test ()
{
IWebSiteConfiguration mockConfig = null;
// setup mock instance and expectation via
// NUnit.Mocks, NMock, or Moq
MyClass myClass = new MyClass (mockConfig);
myClass.DoSomething ();
// verify results
}
This also serves as a practical introduction to Dependency Injection [DI]. It's simply the practice of passing, or "injecting", references of services [eg your web site configuration class] to the consumer, rather than having the consumer invoke the service directly [eg via static singleton class].
Hope this helps :)
A DynamicMock creates a new object in-memory that represents the interface, or marshallable (inherits from MarshalByRef) class you want to mock.
Try this:
var _websiteConfigurationMock = new DynamicMock(typeof(WebSiteConfiguration));
_websiteConfigurationMock.ExpectAndReturn("getCodeByCodeNameAndType", code);
WebSiteConfiguration conf = (WebSiteConfiguration)_websiteConfigurationMock.MockInstance;
var x = conf.getCodeByCodeNameAndType("CATALOG_Brands_MinQty", item.Catalog);
Note that the third line there will not work unless WebSiteConfiguration inherits from MarshalByRef.
What you typically do is mock an interface and get a new object that implements this interface, but behaves the way you've configured it to do, without having to go and make a concrete type for it, so I'm not entirely sure what you're doing is going to work unless you employ a better isolation framework, like TypeMock that can intercept calls to static methods/properties in existing objects.
Seems there is a kind of solution for this using reflection, or maybe I totally misunderstood this.
It is discussed here:
http://www.geekbeing.com/2010/05/23/how-to-unit-test-singleton-hack-in-c
Could it really works?
public class TestableSingleton : SingletonClass
{
public TestableSingleton ()
{
FieldInfo fieldInfo = typeof(SingletonClass)
.GetField("_instance",
BindingFlags.Static | BindingFlags.NonPublic);
fieldInfo.SetValue(Instance, this);
}
}
Project availabe on https://github.com/rbabreu/TestableSingleton
Actually I could not compile it on Visual Studio since the SingletonClass would have a private constructor. If someone get it to work would be great to avoid the overhead of adapter pattern.

Categories