Any suggestions for improvement on this style for BDD/TDD? - c#

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.

Related

Temporarily storing and re-setting a property value in C#

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.
};
}

Mocking a class with private ctor and static create method and private id property

I am trying to use AutoFixture to simplify my life.
How do I mock a class with
non-public constructor and
non-public Id and
static 'Create' method?
Example
public class User
{
private User(){}
/// <summary>
/// Created by Database...
/// </summary>
public long? Id { get; protected set; }
public string Name { get; protected set; }
public static User Create(string name)
{
var user = new User {Name = name};
return user;
}
}
I've tried using a combo of Factory and SpecimenBuilder:
[Fact]
public void CreatingUserWithId_Should_Work_UsingFactoryAndSpecimenBuilder()
{
IFixture fixture = new Fixture().Customize(new AutoFakeItEasyCustomization());
fixture.Customizations.Add(new UserBuilder());
fixture.Customize<User>(o => o.FromFactory(() => User.Create("foo")));
var user = fixture.Create<User>();
user.Should().NotBeNull();
user.Id.Should().HaveValue();
}
with
public class UserBuilder : ISpecimenBuilder
{
public object Create(object request, ISpecimenContext context)
{
var pi = request as PropertyInfo;
if (pi == null) return new NoSpecimen(request);
// The following code only works for public properties... :-(
if (pi.Name == "Id" && pi.PropertyType == typeof (long?)) return 42;
return new NoSpecimen(request);
}
}
A demo C# solution is available at https://github.com/draptik/MockingStaticCreate
Thankful for any pointers,
Patrick
AF will do the right thing (User.Create() with an anonymous name arg) with no customizations whatsoever.
The only missing bit is setting the Id. Which is a question you'll have to answer for yourself -- how should your consuming code do this in the first place ? When you've decided, you could do fixture.Customize<User>( c => c.FromFactory( User.Create).Do( x => ???)
Perhaps you could consider exposing a ctor that takes an id too. Then you can do a Customize<User> ... GreedyConstructorQuery.
If your ORM is doing some wacky reflection and you like that and/or can't route around it you get to choose whether for your tests you should:
a) do that too - if that's relevant to a given test or set of tests
b) consider that to be something that just works
Regarding mixing mocking and feeding in of values to an Entity or Value object - Don't do that (Mark Seemann's Commands vs Queries article might help you here). The fact that you seem to be needing/wanting to do so makes it seems you're trying to be too ambitions in individual tests - are you finding the simplest thing to test and trying to have a single Assert testing one thing with minimal setup.
Go buy the GOOS book - it'll help you figure out ways of balancing these kinds of trade-offs.

.NET humble object example

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.

Can AutoFixture execute a delegate at object creation time?

I'm looking to customize the creation-time behavior of AutoFixture such that I can set up some dependent objects after the properties of the fixture have been generated and assigned.
For example, suppose I have a method that customizes a User because its IsDeleted property always has to be false for a certain set of tests:
public class User
{
public int Id { get; set; }
public string Name { get; set; }
public bool IsDeleted { get; set; }
}
public static ObjectBuilder<User> BuildUser(this Fixture f)
{
return f.Build<User>().With(u => u.IsDeleted, false);
}
(I hand an ObjectBuilder back to the test so it can further customize the fixture if necessary.)
What I'd like to do is automatically associate that user with an anonymous collection by its Id at creation time, but I can't do this as-is because Id has not been generated by the time I hand the return value back to the unit test proper. Here's the sort of thing I'm trying to do:
public static ObjectBuilder<User> BuildUserIn(this Fixture f, UserCollection uc)
{
return f.Build<User>()
.With(u => u.IsDeleted, false);
.AfterCreation(u =>
{
var relation = f.Build<UserCollectionMembership>()
.With(ucm => ucm.UserCollectionId, uc.Id)
.With(ucm => ucm.UserId, u.Id)
.CreateAnonymous();
Repository.Install(relation);
}
}
Is something like this possible? Or perhaps there is a better way to accomplish my goal of creating an anonymous object graph?
For the Build method, this isn't possible, and probably never will be, because there are much better options available.
First of all, it should never be necessary to write static helper methods around the Build method. The Build method is for truly one-off initializations where one needs to define property or field values before the fact.
I.e. imagine a class like this:
public class MyClass
{
private string txt;
public string SomeWeirdText
{
get { return this.txt; }
set
{
if (value != "bar")
throw new ArgumentException();
this.txt = value;
}
}
}
In this (contrived) example, a straight fixture.CreateAnonymous<MyClass> is going to throw because it's going to attempt to assign something other than "bar" to the property.
In a one-off scenario, one can use the Build method to escape this problem. One example is simply to set the value explicitly to "bar":
var mc =
fixture.Build<MyClass>().With(x => x.SomeWeirdText, "bar").CreateAnonymous();
However, even easier would be to just omit that property:
var mc =
fixture.Build<MyClass>().Without(x => x.SomeWeirdText).CreateAnonymous();
However, once you start wanting to do this repeatedly, there are better options. AutoFixture has a very sophisticated and customizable engine for defining how things get created.
As a start, one could start by moving the omission of the property into a customization, like this:
fixture.Customize<MyClass>(c => c.Without(x => x.SomeWeirdText));
Now, whenever the fixture creates an instance of MyClass, it's just going to skip that property altogether. You can still assign a value afterwards:
var mc = fixture.CreateAnonymous<MyClass>();
my.SomeWeirdText = "bar";
If you want something more sophisticated, you can implement a custom ISpecimenBuilder. If you want to run some custom code after the instance has been created, you can decorate your own ISpecimenBuilder with a Postprocessor and supply a delegate. That might look something like this:
fixture.Customizations.Add(
new Postprocessor(yourCustomSpecimenBuilder, obj =>
{ */ do something to obj here */ }));
(BTW, are you still on AutoFixture 1.0? IIRC, there hasn't been an ObjectBuilder<T> around since then...)
There's a useful discussion on this topic on the AutoFixture CodePlex site.
I believe my postprocessor Customization linked over there should help you. Example usage:
class AutoControllerDataAttribute : AutoDataAttribute
{
public AutoControllerDataAttribute()
: this( new Fixture() )
{
}
public AutoControllerDataAttribute( IFixture fixture )
: base( fixture )
{
fixture.Customize( new AutoMoqCustomization() );
fixture.Customize( new ApplyControllerContextCustomization() );
}
class ApplyControllerContextCustomization : PostProcessWhereIsACustomization<Controller>
{
public ApplyControllerContextCustomization()
: base( PostProcess )
{
}
static void PostProcess( Controller controller )
{
controller.FakeControllerContext();
// etc. - add stuff you want to happen after the instance has been created

Design Patterns Recommendation for Filtering Option

I am thinking to create a filter object which filters and delete everything like html tags from a context. But I want it to be independent which means the design pattern I can apply will help me to add more filters in the future without effecting the current codes. I thought Abstract Factory but it seems it ain't gonna work out the way I want. So maybe builder but it looks same. I don't know I am kinda confused, some one please recommend me a design pattern which can solve my problem but before that let me elaborate the problem a little bit.
Lets say I have a class which has Description field or property what ever. And I need filters which remove the things I want from this Description property. So whenever I apply the filter I can add more filter in underlying tier. So instead of re-touching the Description field, I can easily add more filters and all the filters will run for Description field and delete whatever they are supposed to delete from the Description context.
I hope I could describe my problem. I think some of you ran into the same situation before.
Thanks in advance...
Edit :
I actually want to create filters as types/classes instead of regular methods or whatever. Like :
class TextFilter : IFilter
{
private string something;
public string Awesome {get;set;}
public string FilterYo(string textFiltered)
{
// Do filtering
}
}
class HtmlFilter : IFilter
{
private string something;
private string iGotSomething;
public string Awesome {get;set;}
public string FilterYo(string textFiltered)
{
// Do filtering
}
}
class Main
{
protected void Main(object sender, EventArgs e)
{
InputClass input = new InputClass();
string filtered = new StartFiltering().Filter(input.Description); // at this moment, my input class shouldn't know anything about filters or something. I don't know if it makes any sense but this is what in my mind.
}
}
At this point if I want to apply Abstract Factory which would be meaningless or Builder as well. Because I don't want a particular thing, I need all of them kinda.
Thanks for your answers by the way.
Edit 2 - Possible Answer for Me
Okay lets think about strategy pattern with interfaces rather than delegates.
interface IFilter //Strategy interface
{
string Filter(string text);
}
class LinkFilter:IFilter //Strategy concrete class
{
public string Filter(string text)
{
//filter link tags and return pure text;
}
}
class PictureFilter:IFilter //Strategy concrete class
{
public string Filter(string text)
{
//filter links and return pure text;
}
}
class Context
{
private IFilter _filter;
private string _text;
public Context(IFilter filter,string text)
{
this._filter = filter;
this._text = text;
}
public void UpdateFilter(IFilter filter)
{
this._filter = filter;
}
public string RunFilter()
{
this._text = _filter.Filter(this._text);
return this._text;
}
}
class MainProgram
{
static void Main()
{
MyObject obj = new MyObject();
LinkFilter lfilter = new LinkFilter();
PictureFilter pfilter = new PictureFilter();
Context con = new Context(lfilter,obj.Description);
string desc = con.RunFilter();
con.UpdateFilter(pfilter);
desc = con.RunFilter();
}
}
Why don't you just go light weight: Define your filter as a Func<string, string>. If you keep these in a collection (List<Func<string, string>>), you can just do:
var text = myObject.DescriptionProperty
foreach (var func in myFuncList)
{
text = func(text);
}
You can also use Linq to shorten the above loop:
var text = myFuncList.Aggregate(text, (seed, func) => func(seed));
This way, you don't have to define a class hierarchy for filtering. This is good for the environment, since we will be running out of classes and namespaces very soon!
To wrap things up, I suggest you subclass List:
public class FilterCollection : List<Func<string, string>>
{
public string Filter(string text)
{
return this.Aggregate(text, (seed, func) => func(seed));
}
}
Have you looked at the strategy pattern? It allows you to swap algorithms.
If that is not what you are looking for, perhaps the decorator pattern will be more suitable. This will allow you to wrap filters and apply multiple ones if needed.
To me this sounds like the Strategy pattern.
Could be something like this (the code is in VB):
Function GetFilteredDescription(ByVal iSpecificFilterFunction As AbstractFilterFunction) As Result
Return iSpecificFilterFunction.Filter(Me.description)
End Function
Note: the GetFilteredDescription is member function of your class.
You can use below patterns:
Strategy Pattern for different Filter types
Chain of Responsibility for your filter stack (You can add Command Pattern here for different chains in a multitasking environment, or you can implement priority based chain or so on )
Builder or Abstract Factory for Filter instance creations.
What about Provider pattern? http://msdn.microsoft.com/en-us/library/ms972319.aspx
It is similar to Strategy, and is used in Microsoft products thoroughly.

Categories