I have two classes: Foo and FooBar. FooBar derives from Foo. I have a factory class that, given parameters, decides which object to instantiate and return.
So I want to have unit tests that verify my factory class is working properly and returning the proper instances.
This is somewhat clean for FooBar:
[Test]
public void FooBarFactoryTest()
{
var testObj = FooFactory(paramsForFooBarOnly);
Assert.IsInstanceOf<FooBar>(testObj);
}
But for Foo, it's rather messy:
[Test]
public void FooFactoryTest()
{
var testObj = FooFactory(paramsForFooOnly);
Assert.IsInstanceOf<Foo>(testObj); //An instance of FooBar would pass this assert
Assert.IsNotInstanceOf<FooBar>(testObj); //Can't have just this assert.
}
Is there any way I can re-write this second test to follow the paradigm of "One assert per test?" Preferably, I'd also like to have tests that account for potential additional derivations of Foo or FooBar.
Sure, just use Assert.IsTrue:
Assert.IsTrue(testObj.GetType() == typeof(Foo));
Don't feel like you have to choose only from the various "helper" methods from NUnit.
Related
Looking at this question got me wondering if something similar is possible using the dark reflection ways of C#.
Say I have this code:
public class Foo
{
public void FooPrint() // can't change this implementation
{
Console.Write("Foo");
}
}
public class Bar
{
public Foo foo = new Foo();
public Bar()
{
//do some reflection magic with member foo here ?
}
public void FooPrintRewritten()
{
Console.Write("Haha, only for Bar.foo.");
}
}
class Program
{
static void Main(string[] args)
{
Foo a = new Foo();
a.FooPrint(); // should still print "Foo"
Bar bar = new Bar();
bar.foo.FooPrint(); // should print "Haha, only for Bar.foo."
}
}
Is what I ask for in the inlined comments in any way possible? Is there a way to re-bind a method call to another method for only a specific variable?
Yes I know this is ridiculous, no this shouldn't ever be used in production code. This is for the sake of curiosity.
Other answers have suggested ways in which you can achieve what you want on a functional level, which is arguably the sane thing to do, but I'll tackle the question directly: can this be done changing no code in the question except the implementation of Bar.Bar(), keeping Bar.foo of type Foo and changing nothing about Foo?
The answer is no. You cannot change the method table for a single object, which is basically what you're asking for here. The method table is part of the type, not the instance. If an expression f is of type Foo, and FooPrint is a non-virtual method of Foo, then the call f.FooPrint() will always resolve to Foo.FooPrint. Even worse, the compiler might choose to inline the call since that's obviously a safe optimization*. Where are your dark reflection ways now?
The only way to achieve this is to convince the compiler that calls to Foo.FooPrint should be treated specially, taking the instance into consideration. There are a few ways of doing so:
Foo.FooPrint could be made a delegate. The targets of a delegate call are specific per instance of the delegate.
Foo.FooPrint could be made a virtual, abstract or interface method. All of these are resolved based on the runtime type of the instance. Simply derive a class from Foo and away you go.
Foo could inherit from MarshalByRefObject. An MBRO, as it's commonly called, is treated specially by the jitter since (as the name implies) calls may need to be marshalled back. In particular, if Foo was an MBRO, you could create a RealProxy for it that will cough up a transparent proxy that resembles a real, actual Foo in almost all ways, right down to GetType(), except that you get to choose how calls are actually handled.
All of these approaches are used by various mocking/interceptor/proxy libraries, all of them require some change to Foo. The only approaches that require no (textual) change to Foo are those that rewrite the IL involved, like PostSharp or Microsoft Fakes, but I'd consider that cheating for purposes of this question.
* Technically, the C# standard says nothing about either method tables or permissible ways of inlining since those are implementation details, but it does say that Foo.FooPrint is always resolved in only one way without considering the instance (except that it must not be null).
Actually, there is a case for this type of behaviour under SRP of SOLID if you needed to separate implementations to maintain the principle (depending on how strictly you are adhering to SOLID ofc).
It's called the Interceptor pattern and used by Mocking libraries such as Moq.
Have a look at the following article on the subject for a good example of how the pattern can be used: C#: Why Decorate When You Can Intercept
Here's another way of overriding (virtual) methods when you instantiate a class
class Program
{
static void Main(string[] args)
{
Foo a = new Foo();
a.FooPrint(); // should still print "Foo"
Bar bar = new Bar();
bar.foo.FooPrint(); // should print "Haha, only for Bar.foo."
Console.Read();
}
}
public class Foo
{
public Action FooPrint = () => Console.WriteLine("Foo");
}
public class Bar
{
public Foo foo = new Foo()
{
FooPrint = () => Console.WriteLine("Haha, only for Bar.foo.")
};
}
this post explains how to make an override right when you instantiate a class.
However, it uses Func which requires a method which contains a return type that isnt void, thats why you'll want to use Action instead, as explained here
What about this, with still the same usage:
public class Wrapper : Foo
{
public new void FooPrint()
{
Console.Write("Haha, only for Bar.foo.");
}
}
public class Bar
{
public Wrapper foo = new Wrapper();
}
Is there a way to assert that my mocked object was "gotten" ?
public class Car
{
private readonly IValidationDict _validationDict;
public Car(IValidationDict validationDict)
{
_validationDict = validationDict;
}
public void Go()
{
var myValidation = _validationDict; //I would like to assert that _validationDict was indeed assigned to another variable or "gotten"
}
}
In my unit test I would have something like:
var mock = new Mock<IValidationDict>();
var sut = new Car(IValidationDict.Object);
Is there a way to assert that my mocked object was "gotten" ?
No, there is no way to verify that your mock object was used as part of the assignment. The assignment of myValidation happens outside the bounds of the Moq framework and therefore Moq can't do any interception to track it.
As #Lee state, there is an assumption that myValidation is used somewhere else and the use of that variable (which will be a mocked instance) can be checked.
One alternative if you must know if your mock was accessed would be to create a factory class that has a method for obtaining your validation dictionary (something like GetValidation) and then pass a mocked factory to your Car and verify that the GetValidation method was called on the factory.
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.
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.
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.