I'm currently attempting to implement the humble object design pattern. The only resource I can find regarding this is from the xunit testing web site. Unfortunately, I don't really understand it despite reading it several times. Is there perhaps another name this pattern goes by?
Here is what I have thus far.
public interface IHumbleExchangeWebService
{
GetItemResult BindToItems(IEnumerable<string> itemIds);
SyncFolderItemsResult Sync();
void Subscribe();
}
public class ExchangeWebServiceAdapter
{
private readonly IHumbleExchangeWebService _humbleExchangeWebService;
public ExchangeWebServiceAdapter(
IHumbleExchangeWebService humbleExchangeWebService)
{
_humbleExchangeWebService = humbleExchangeWebService;
Start();
}
private void Start()
{
SyncFolderItemsResult syncFolderItemsResults;
while(true)
{
syncFolderItemsResults = _humbleExchangeWebService.Sync();
if(syncFolderItemsResults != null)
break;
}
ProcessSyncResults(syncFolderItemsResults);
LastSyncDateTime = Time.Now;
_humbleExchangeWebService.Subscribe();
}
private void ProcessSyncResults(SyncFolderItemsResult syncFolderItemsResults)
{
if (syncFolderItemsResults.Count <= 0) return;
var missedItemIds = syncFolderItemsResults.ItemChange
.ToList()
.Select(x => x.ExchangeItem.ItemId);
_humbleExchangeWebService.BindToItems(missedItemIds);
}
public DateTime LastSyncDateTime { get; private set; }
}
And as for the testing:
[TestFixture]
public class Tests
{
private Mock<IHumbleExchangeWebService> _humbleExchangeWebServiceMock;
[SetUp]
public void SetUp()
{
_humbleExchangeWebServiceMock = new Mock<IHumbleExchangeWebService>();
}
[Test]
public void OnInitialiseWillSyncBeforeSubscribing()
{
var callOrder = 0;
_humbleExchangeWebServiceMock
.Setup(x => x.Sync())
.Returns(() => new SyncFolderItemsResult(0, false, String.Empty, GetExchangeItemChangeList()))
.Callback(() => Assert.That(callOrder++, Is.EqualTo(0)));
_humbleExchangeWebServiceMock
.Setup(x => x.Subscribe())
.Callback(() => Assert.That(callOrder++, Is.EqualTo(1)));
var service = GetConstructedService();
_humbleExchangeWebServiceMock.Verify(x => x.Sync(), Times.Once());
_humbleExchangeWebServiceMock.Verify(x => x.Subscribe(), Times.Once());
}
[Test]
public void WhenSyncingIsCompleteWillProcessMissingItem()
{
_humbleExchangeWebServiceMock
.Setup(x => x.Sync())
.Returns(new SyncFolderItemsResult(1, false, It.IsAny<string>(), GetExchangeItemChangeList()));
var service = GetConstructedService();
_humbleExchangeWebServiceMock.Verify(x => x.BindToItems(It.IsAny<IEnumerable<string>>()));
}
[Test]
public void BindingItemsWillProcess()
{
_humbleExchangeWebServiceMock
.Setup(x => x.Sync())
.Returns(new SyncFolderItemsResult(1, false, It.IsAny<string>(), GetExchangeItemChangeList()));
var service = GetConstructedService();
_humbleExchangeWebServiceMock
.Verify(x => x.BindToItems(new []{"AAA", "BBB", "CCC", "DDD"}), Times.Once());
_humbleExchangeWebServiceMock.VerifyAll();
}
private ExchangeWebServiceAdapter GetConstructedService()
{
return new ExchangeWebServiceAdapter(_humbleExchangeWebServiceMock.Object);
}
private IEnumerable<ExchangeItemChange> GetExchangeItemChangeList()
{
yield return new ExchangeItemChange(ChangeType.Create, new ExchangeItem("AAA"));
yield return new ExchangeItemChange(ChangeType.Create, new ExchangeItem("BBB"));
yield return new ExchangeItemChange(ChangeType.Create, new ExchangeItem("CCC"));
yield return new ExchangeItemChange(ChangeType.Create, new ExchangeItem("DDD"));
}
}
Essentially, I'm simply wondering if I'm on the right track of making the humble object dumb. What I mean is that is it the proper way to extract all conditions that I can easily unit test into a wrapper class (e.g. ExchangeWebServiceAdapter).
A good rule of thumb when trying to implement the humble object pattern is to look at the object you just created and ask yourself how you're going to test all the logic inside it. If you have a general idea of what you're going to do within 10 seconds and it doesn't cause you to groan out loud, you're probably fine. If it takes you any longer than that or if it causes you pain to think about it, you've probably made a mistake somewhere.
As far as understanding of the humble pattern, you can think of it like a car assembly line; the thing that makes those massive lines work is the fact that everything is interchangeable. Engines only Go, heaters only Heat, etc. The simplest way to keep it straight in your mind is to name your classes such that they are a concrete object, and then get rid of anything that doesn't fall under what that object should do. In your specific example, you've named your class an 'adapter'. Okay, so what is it adapting FROM and TO? What two incompatible things is it making compatible? I'd guess part of your confusion is that your class is misnamed or too broad at this point in time. As your understanding grows so will your vocabulary and you might find it's perfectly fine at that point. If you're just learning the pattern, it will inhibit your understanding to jump straight to programmer jargon; a lot of these words we use have poorly defined meanings.
To put it more concretely, if a Starter needs to get other information or kick other resources to finish Starting, that's fine; it's just that those other resources should be clearly named, abstracted out to other classes, and tested separately.
You've done a decent job of making the objects as you've presented them trivial, but obviously you'll need to worry about the implementation of your interface being dumb enough as well, when you get to that point.
Hopefully this helps; the humble object pattern is both distinct and very similar to the ideal of loose coupling that you will hear people talk about all the time. The humble object pattern is simply a specific prescribed way of achieving loose coupling with a bunch of objects that traditionally resist it.
Related
I'm using MoQ in C# to do some Unit tests/BDD tests, and I've often the need of generating the same object twice(because it will be potentially used in dictionary). Or something 99% the same but just with a different ID.
Is there a way to "clone" the Mock definition? Or to generate two objects with the same definition?
You should create a helper method that constructs that takes in some parameters to construct the Mock object.
[Test]
public void MyTest()
{
Mock<ITestObject> myMock = CreateObject(1);
ITestObject obj = myMock.Object;
}
private Mock<ITestObject> CreateObject(int id)
{
Mock<ITestObject> mock = new Mock<ITestObject>();
mock.SetupGet(o => o.ID).Returns(id);
return mock;
}
private interface ITestObject
{
int ID { get; set; }
}
If you just need a collection of data to unit test with, you may consider something like AutoFixture as well. It can work with Moq in the case of classes you want to mock. You teach AutoFixture how to create YourClass, and you can even set rules like "my IDs should be strings with capital letters and no more than X amount of them."
Then you'd just use autofixture.
var fixture = new Fixture();
var tetsClasses = fixture.CreateMany<TestClass>();
This is really just to give you an idea. You can do quite a but more with it, and it plays really well with Moq.
An alternative is to use a data builder pattern to create your data. So you could start with something simple and just keep adding onto it as you find new edge cases on how you need to build the data. Just build a fluent API on it and build the data however you want.
internal class TestClassBuilder<T> : where T : TestClass
{
int Id {get; set;}
public T WithId(int id)
{
this.Id = id;
return this;
}
public virtual T Build()
{
return new T()
{
if(this.Id)
Id = this.Id; // if you chose to set it, then assign it
else
Id = GetRandomId() // you can figure a solution here
}
}
}
Then call it like:
var stubOne = TestClassBuilder.WithId(1).Build();
You can extend it to build a list if you want.
I like fluent APIs on data builders, because you can start to tell your story with the methods you create, and it keeps your Arrange section neat and tidy.
Example:
var UnderAgeCustomer = new CustomerBuilder
.UnderAge
.WithFakeId
.InACrowd
.LooksYoung
.Build()
You could even add on
public static implicit operator T(TestClassBuilder<T> builder)
{
return builder.Build();
}
And you wouldn't need to use the .Build() part all the time (I think build adds unnecessary noise). Just don't try assigning that to a var, it won't work.
TestClass MockTwo = TestClassBuilder.WithId(2);
I would say you could also use a fixture pattern to track of all this ... but between that and the databuilder, you may as well use AutoFixture and Moq as I suggested :)
When I'm writing tests in a specific code base, I often need set a static property before my newly added code, and re-set it back when leaving. Example
public void SomeMethod(){
val oldVal = Notifier.DoNotify;
Notifier.DoNotify = false;
// Some code...
Notifier.DoNotify = oldVal;
}
I think this way is ugly and I want something nicer and which also makes it harder forget to re-set the value.
I tried cooking something up and got this. I see some benefits, but it's a pretty talky solution.
public class ValueHolder<T> : IDisposable
{
private readonly Action<T> setter;
private readonly T oldVal;
public ValueHolder(Func<T> getter, T tempVal, Action<T> setter)
{
this.setter = setter;
oldVal = getter();
setter(tempVal);
}
public void Dispose()
{
setter(oldVal);
}
}
Which then is used like
public void SomeMethod(){
using(new ValueHolder<bool>(() => Notifier.DoNotify, false, (b) => Notifier.DoNotify(b)) {
// Do something ...
}
}
What is a good solution to this?
(Edit removed reference to testing. Seemed to distract from what I wanted to ask)
There's a couple things you can do to make it a little easier to write. I would try to leverage whatever testing framework you are using to help running some setup/cleanup code before and after the test. But barring that here some tips that can cut down on the boiler plate.
First we can create a helper class that will cut down a little on the boilerplate for creating a ValueHolder<T> instance. I'll use LINQ Expressions to create the getter and setter delegates automatically rather than requiring the caller pass in both a getter and setter (although that could still be useful in advanced cases).
public class ValueHolder
{
public static ValueHolder<T> Create<T>(Expression<Func<T>> staticProp, T tempVal)
{
var ex = (MemberExpression)staticProp.Body;
var prop = (PropertyInfo)ex.Member;
var getter = (Func<T>)Delegate.CreateDelegate(typeof(Func<T>), prop.GetGetMethod());
var setter = (Action<T>)Delegate.CreateDelegate(typeof(Action<T>), prop.GetSetMethod());
return new ValueHolder<T>(getter, tempVal, setter);
}
}
This makes the creation a little more terse
ValueHolder.Create(() => Notify.DoNotify, false);
Second, you will probably need to set a few of these and a big using is kind of ugly. My answer to this question provides a way to handle this scenario in a slightly easier way using a class that inherits from List<T> which is also IDisposable. Combining these you could make your setup much simpler:
public void SomeTestMethod()
{
// before any state has change.
using (Setup())
{
// Test code.
}
// the cleanup code has run so the state is reset here.
}
private static IDisposable Setup()
{
return new DisposableList() {
ValueHolder.Create(() => Notify.DoNotify, false),
ValueHolder.Create(() => ConnectionManager.MaxConnections, 100),
ValueHolder.Create(() => SomeClass.SomeProp, 2.5),
// etc., I think you get the idea.
};
}
The problem
I have a pretty big application that makes use of a bunch of other services.
For testing scenarios I don't want my unit tests to rely on third party systems, so I want to replace the services with fakes or mocks, or whatever.
I've already done most of the hard labor, and replaced the concrete services with a IService. The concrete Service is wired in with a DI framework
Now I want to replace those with random generated fakes.
The code
Interface of example service:
public interface ISimpleService
{
int Fizz(int input);
string Buzz(string input);
}
Interface of example service factory:
public interface ISimpleServiceFactory
{
ISimpleService Create();
}
Implementation simple as possible
public static void Main(string[] args)
{
var fixture = new Fixture().Customize(new AutoMoqCustomization());
var service = fixture.Create<ISimpleService>();
var fizzResult = service.Fizz(42);
var buzzResult = service.Buzz("I'd like something random...");
}
This shows what I basically want. I just want autofixture to create some dynamic proxy object for me, with methods that return something random of the type specified in the interface...
Note that I've used AutoMoq here, because by default Fixture doesnt want to create objects from interfaces, but I've tried other frameworks too: FakeItEasy, AutoRhinoMock
Workaround
Implementation that kind of works by manually setting everything
public static void Main(string[] args)
{
var fixture = new Fixture().Customize(new AutoMoqCustomization());
var serviceMock = fixture.Create<Mock<ISimpleService>>();
// These two lines below cause the magic now
serviceMock.Setup(x => x.Fizz(It.IsAny<int>())).Returns(fixture.Create<int>());
serviceMock.Setup(x => x.Buzz(It.IsAny<string>())).Returns(fixture.Create<string>());
var service = serviceMock.Object;
var fizzResult = service.Fizz(42);
var buzzResult = service.Buzz("I'd like something random...");
}
This does give me the desired result: fizzResult with a random int, buzzResult with a random string (a guid by default)
However, this is only a small example, my actual service references are a lot bigger, with up to 100s of methods... (they are external soap services etc, can't help it)
I don't want to set up everything manually, if theres a generic solution, that would be great...
An implementation for factories that kind of works by manually setting everything
So, as you might have noticed, I've also posted a ISimpleServiceFactory interface. This resembles the actual situation, since the actual concrete ISimpleService requires a bunch of configuration.
So, if we'd use the kind of working solution, we'd come to this:
public static void Main(string[] args)
{
var fixture = new Fixture().Customize(new AutoMoqCustomization());
var serviceFactoryMock = fixture.Create<Mock<ISimpleServiceFactory>>();
var serviceMockDelegate = new Func<ISimpleService>(() =>
{
var serviceMock = fixture.Create<Mock<ISimpleService>>();
serviceMock.Setup(x => x.Fizz(It.IsAny<int>())).Returns(fixture.Create<int>());
serviceMock.Setup(x => x.Buzz(It.IsAny<string>())).Returns(fixture.Create<string>());
return serviceMock.Object;
});
serviceFactoryMock.Setup(x => x.Create()).Returns(serviceMockDelegate);
var service = serviceFactoryMock.Object.Create();
var fizzResult = service.Fizz(42);
var buzzResult = service.Buzz("I'd like something random...");
}
This seems to be getting a bit of a mess, and this is a pretty small interface.
The actual services are many levels deep, with 100s of methods.
For methods in my code that require specific conditions I'll obviously still manually set those conditions, but everything else should be random values by default. Generating large amounts of random objects allows for a bit of fuzzy testing too
Is there a way to automatically generate random objects without all this manual setting up?
You don't need a factory nor do you need to setup every method within your interfaces, if I understand correctly you simply want to use Fixture to create a proxy which returns random values for every method you invoke on that proxy. Instead of using AutoMoqCustomization use AutoConfiguredMoqCustomization. It's all in the nuget package called Fixture.AutoMoq.
class Program
{
static void Main(string[] args)
{
}
}
[TestFixture]
public class program
{
[Test]
public void some_test()
{
var fixture = new Fixture();
fixture.Customize(new AutoConfiguredMoqCustomization());
var simpleServices = fixture.CreateMany<ISimpleService>();
foreach (var simpleService in simpleServices)
{
string randomString = simpleService.Buzz("hello");
int randomInt = simpleService.Fizz(15);
}
}
}
public interface ISimpleService
{
int Fizz(int input);
string Buzz(string input);
}
Using FakeItEasy, how do I check to see if my object's method calls another method on this same object?
The Test:
[TestMethod]
public void EatBanana_CallsWillEat()
{
var banana = new Banana();
var myMonkey = new Monkey();
myMonkey.EatBanana(banana);
//this throws an ArgumentException, because myMonkey is a real instance, not a fake
A.CallTo(() => myMonkey.WillEat(banana)
.MustHaveHappened();
}
The Class:
public class MyMonkey {
private readonly IMonkeyRepo _monkeyRepo;
public MyMonkey(IMonkeyRepo monkeyRepo) {
_monkeyRepo = monkeyRepo;
}
public void EatBanana(Banana banana) {
//make sure the monkey will eat the banana
if (!this.WillEat(banana)) {
return;
}
//do things here
}
public bool WillEat(Banana banana) {
return !banana.IsRotten;
}
}
I'm open to suggestions. If I'm going about this all wrong, please let me know.
Why are you mocking tested object? What exactly are you trying to test? The verification that call to WillEat happened is of little value. What information does it server to consumer? After all, consumer doesn't care how method is implemented. Consumer cares what are the results.
What happens when monkey eats banana that is not rotten? Your test should answer this question:
[TestMethod]
public void EatBanana_CAUSES_WHAT_WhenBananaIsNotRotten()
{
var repo = A.Fake<IMonkeyRepo>();
var monkey = new Monkey(repo);
var freshBanana = new Banana { IsRotten = false };
monkey.EatBanana(freshBanana);
// verifications here depend on what you expect from
// monkey eating fresh banana
}
Note that you can make all sort of verifications to IMonkeyRepo, which is properly faked and injected here.
It's possible to do this. If the WillEat method were virtual - otherwise FakeItEasy won't be able to fake it out.
With that change, you could do this:
[TestMethod]
public void EatBanana_CallsWillEat()
{
var fakeMonkey = A.Fake<MyMonkey>();
fakeMonkey.EatBanana(new Banana());
A.CallTo(()=>fakeMonkey.WillEat(A<Banana>._)).MustHaveHappened();
}
I'm still not convinced it's a good idea (as I ranted in the comments) - I think you'd be better off relying on other observable behaviour, but I'm not familiar with your system. If you think this is the best way to go, the example code should work for you.
I was tinkering with doing the setups with our unit test specifciations which go like
Specification for SUT when behaviour X happens in scenario Y
Given that this thing
And also this other thing
When I do X...
Then It should do ...
And It should also do ...
I wrapped each of the steps of the GivenThat in Actions... any feed back whether separating with Actions is good / bad / or better way to make the GivenThat clear?
/// <summary>
/// Given a product is setup for injection
/// And Product Image Factory Is Stubbed();
/// And Product Size Is Stubbed();
/// And Drawing Scale Is Stubbed();
/// And Product Type Is Stubbed();
/// </summary>
protected override void GivenThat()
{
base.GivenThat();
Action givenThatAProductIsSetupforInjection = () =>
{
var randomGenerator = new RandomGenerator();
this.Position = randomGenerator.Generate<Point>();
this.Product = new Diffuser
{
Size =
new RectangularProductSize(
2.Inches()),
Position = this.Position,
ProductType =
Dep<IProductType>()
};
};
Action andProductImageFactoryIsStubbed = () => Dep<IProductBitmapImageFactory>().Stub(f => f.GetInstance(Dep<IProductType>())).Return(ExpectedBitmapImage);
Action andProductSizeIsStubbed = () =>
{
Stub<IDisplacementProduct, IProductSize>(p => p.Size);
var productBounds = new ProductBounds(Width.Feet(), Height.Feet());
Dep<IProductSize>().Stub(s => s.Bounds).Return(productBounds);
};
Action andDrawingScaleIsStubbed = () => Dep<IDrawingScale>().Stub(s => s.PixelsPerFoot).Return(PixelsPerFoot);
Action andProductTypeIsStubbed = () => Stub<IDisplacementProduct, IProductType>(p => p.ProductType);
givenThatAProductIsSetupforInjection();
andProductImageFactoryIsStubbed();
andProductSizeIsStubbed();
andDrawingScaleIsStubbed();
andProductTypeIsStubbed();
}
Put them in separate methods so that you can compose them in other givens. Also, use underscores to replace spaces (instead of camel case). Also, create a method Given_that that takes params of Action delegates.
protected void Given_that(params Action[] preconditions)
{
foreach (var action in preconditions)
{
action();
}
}
...
protected void a_product_is_set_up_for_injection()
{
...
}
protected void product_image_factory_is_stubbed()
{
...
}
etc...
...
Given_that(a_product_is_set_up_for_injection,
product_image_factory_is_stubbed,
product_size_is_stubbed,
drawing_scale_is_stubbed,
product_type_is_stubbed);
That being said, I think the naming of your preconditions are not BDD. They are very technical in nature and do not denote the business need. If you were to tell a non-programmer what you were testing, you would probably not say "the product is stubbed for injection." You would more likely say
Given a displacement product
that is a two inch rectangular diffuser
that has a random position
that has a bitmap
that has a size bounded by feet
that has the expected pixels per foot
Now you can compose your "given" methods with little duplication:
protected [the type of your test class] Given(params Action given)
{
given();
return this;
}
protected void That(params Action[] preconditions)
{
foreach (var precondition in preconditions)
{
precondition();
}
}
Given(a_displacement_product)
.That(is_a_two_inch_rectangular_diffuser,
has_a_random_position,
has_a_bitmap,
has_a_size_bounded_by_feet,
has_the_expected_pixels_per_foot);
Composing your Givens, Whens and Thens in separate methods is a good idea and it's the way for instance SpecFlow (http://www.specflow.org) does it. So if rather want some automation for creating that boring piece of repetetive plumbing, I would really recomend using a tool like SpecFlow. And as a bonus you get a nice reporting tool :)
An other option to make your code a bit more fluent, is to make a little BDD base class. Take a look at Jonas Follesoe's brilliant little BDD DSL up at GitHub: http://gist.github.com/406014;
public abstract class BDD<T> where T : BDD<T>
{
protected T Given { get { return (T)this; } }
protected T And { get { return (T)this; } }
protected T When { get { return (T)this; } }
protected T Then { get { return (T)this; } }
}
And as Michael Meadows point out in his great answer; If you're going the BDD way of doing TDD (which you really should), keep focus on making your spesifications readable to business people. That means; stay away from technical wordings mock, inject, factory, exception, etc.