Asier's thoughts

Blogging about software development


Leave a comment

Automocking dependencies in unit tests for C# with AutoFixture

If you have been unit testing for a while you would have come to the following problem:

You have a class that talks to different classes. These dependencies are injected to your class through the constructor. You would have a test like the this:

    [Fact]
	public void SomeTest()
	{
		var dependency1stub = new Mock<IDependecy1>();
		var dependency2mock = new Mock<IDependecy2>();
		dependency1stub.Setup(x => x.SomeQuery()).Returns(2);

		var sut = new SUT(dependency1stub.Object, dependency2mock.Object); 

		Assert.Equal(4, sut.GetDoubleValue(2));
		dependency2mock.Verify(x => x.SomeComand());
	}

I guess you would have more than one test against this class, probably many. Each of them calling to the constructor of the object with its dependencies.

Now, what happens if you change the dependencies? What happens if you add one dependency extra to this class? You will have to go one by one through all the tests and change the line of code where new SUT(…) is present.

var sut = new SUT(dependency1stub.Object, dependency2mock.Object, dependency3mock.Object);

What if you have dozens or hundreds of tests against that class?? That could be kind of painful! I can already heard you saying..

test are slowing me down!

Well, wait! Bear with me.

First thing to notice here is that using the “new” keyword is a code smell and should be avoided when possible. Each time you use new you are coupling that code to a particular implementation. In this case, we are coupling the tests to construction of the system under test and ultimately to the de injection of its dependencies. We should avoid this as much as possible. Let’s see how we can fix this.

The easiest approach would be to create a test setup and move the object initialisation there, this way that code will get shared through all the methods in the test class. If dependencies change we will have to update JUST the code there.

        private Mock<IDependecy1> _dependency1stub;
        private Mock<IDependecy2> _dependency2mock;
        private SUT _sut;

        public Tests() // Test setup in xUnit is the constructor
        {
            _dependency1stub = new Mock<IDependecy1>();
            _dependency2mock = new Mock<IDependecy2>();

            _sut = new SUT(_dependency1stub.Object, _dependency2mock.Object);
        }

        [Fact]
        public void SomeTest()
        {
            _dependency1stub.Setup(x => x.SomeQuery()).Returns(2);

            Assert.Equal(4, _sut.GetDoubleValue(2));
            _dependency2mock.Verify(x => x.SomeComand());
        }

However, with this approach still we will have to change code. It’s not nice, our code is not open for extesion and closed for modification. We are violating the Open-Closed principle.
Also, what if your system under test is called from different test classes? You will still have to change all setups for those test classes.
You can improve things using a SUT factory. But still you will have to change the code inside the factory each time.

A better approach would be to use a external library like Autofixture that can automock and autoinject those dependencies. We will let Autofixture to do the job of object initialisation for us.

        [Fact]
        public void WithAutoFixture()
        {
            var fixture = new Fixture();
            fixture.Customize(new AutoMoqCustomization()); // set up automocking

            var dependency1stub = fixture.Freeze<Mock<IDependecy1>>();
             var dependency2mock = fixture.Freeze<Mock<IDependecy2>>();
            dependency1stub.Setup(x => x.SomeQuery()).Returns(2);

            var sut = fixture.Create<SUT>(); // initialise object with mocked dependencies 

            Assert.Equal(4, sut.GetDoubleValue(2));
            dependency2mock.Verify(x => x.SomeComand());
        }

If you now add a new dependency to the constructor of the SUT this test still will compile and pass. You don’t care any more about object construction and your tests are not fragile any more!
So you can keep doing TDD and stop complaining how tests are slowing you down!

Happy coding! ūüôā

PS I know you can also do this in Machine.Specifications with Machine.Specifications.AutoMocking or Machines.Fakes. I highly recommend the last one if you are using Machine.Specifications.


Leave a comment

Thinking is the bottleneck

I just spend almost two days with a bug fix at work. The fix was just a one line code change!

This kind of things make you think. We as developers spend a lot more time reading and understanding code than writing it. Knowing where and how to do the code change is the important bit, but getting to there is the difficult bit. Specially when you are dealing with code which is hard to understand.

Many managers (and sadly also some developers) don’t understand that in software development typing is not the bottleneck. It is expected from developers to write loads of code, the more the better, if it’s faster even better. But the thing is that we are problem solvers, not code monkeys. The goal of each feature we release¬†is to solve a particular business problem, not to put some code in a server..

Having this in mind is important to take the right approach. Thinking is the bottleneck . Getting to the solution is the hard bit.

That’s why things like pair programming should be taking into account, two people will get to a solution faster working together than separately. Things like keeping your code “clean” matters, if you write code that shows its intent and is inline with the business domain it would be easier to understand and get to the solution faster.¬†It’s also important to have conversations often with the business because it will make you understand the real problem and get to the solution faster.¬†And many more..

The point I am trying to make here is that you shouldn’t¬†think that we are here to write code, we are here to solve problems!


5 Comments

Care

I got to the conclusion that the successful delivery of software is all down to care.

If you have developers who care they will write clean code, with unit test and follow TDD approach. The code will be easy to change, enabling the business to make quick decisions against the market so they can beat their competitors.

If you have product owners (or project managers) who care they will try to bring the best features to their products. They will speak to developers and testers and define together the best possible solutions and refine their features in the process.

If you have testers who care they will try to understand the features that are being request to be developed. They will stablish conversations with business people and developers so they will know which tests to write in order to verify the product is working as expected.

If you have operations people who care they will enable their systems for easy deployments. They will talk with developers and give them the power to easily change their code in production while giving technical advise.

In general, if you have people who care they will try to do their best while looking for ways to improve.

If you are one of that many companies struggling with your software delivery my advise is simple: hire people who care! That would be the first step, after that everything will come together slowly.


Leave a comment

A new journey

I recently started working as a contractor here in London. London is a great city to work as a developer, there are many many many opportunities. I feel lucky to be honest. Most of jobs are for permanent positions and some of them are¬†even really well paid, but that would be the easy thing to do. And I don’t like easy things..

Been a contractor is challenging. You can’t feel safe like in a permanent job, you can get¬†fired¬†with just a week notice, sometime even less. So you have to proof yourself you are worth it to your employer. Also you have to keep up to date with the latest technologies, methodologies and whatnot. You will get challenged all the time in interviews and you will have to constantly be looking for jobs. Basically, it means embracing a lifestyle that forces you a bit out of your comfort zone. And that’s good!

This is a huge opportunity to  learn. As a contractor you will be moving from one job to another, exploring different business domains, playing with different technologies, being exposed to different ways to develop software and working with many different developers. If we use the Software craftsmanship metaphor it is the same as being a Journeyman. Travelling from one job to another and learning from each before becoming a master.

So let’s begging this journey..


Leave a comment

The only way to go fast is to go well.

– Robert C. Martin

Uncle bob is a big advocate of writing high quality code or clean code as he likes to call it. He says the success of software projects are strongly related in their internal quality. The lower the quality of the code the more difficult will be to make changes to it.

Software projects with low quality will make delivery schedules to get postponed and thus big amounts of money got lost. This will create bigger pressure in the project making developers to go for the quick and dirty way. As a snowball effect quality will go down down down.. Every new change will make the code even worse and harder to make more changes in the future.

Therefore, for a successful delivery of a project quality is paramount. Every day developers will have to keep their code base clean and avoid the quick and dirty option. Even if management is pressuring them! Going dirty will never be quick at the end of the day. The dirty way will slow us down. It will be foolish. Thus, The only way to go fast is to go well.

Practices as unit testing, TDD, mercilessly refactoring, keeping the background cleaner than you found it and giving honest estimates will help in the matter. I like to keep my code clean, taking extra care. Small classes with small methods with the right names, etc.  It is not an easy task to be honest. Just practice and experience can teach you. Still I have much too learn!

Also I highly recommend reading the book Clean code by Robert C. Martin.

Clean code book

Good luck and keep that code clean! ūüôā


Leave a comment

Clean Code Development: Orange Grade

Now that I have finished with the principles from the Red grade I can move on and start with the next grade of the clean code development: the Orange grade.

The principles are:

  • Single Level of Abstraction
  • Single Responsibility Principle
  • Separation of Concerns
  • Source Code Conventions

And the practices:

  • Issue Tracking
  • Automate Tests
  • Eager Reading
  • Code Reviews

I will go through each of the principles during the next weeks and jump to the next grade when finished. I will define the practices of each grade when I come back again in my next iteration through the grades.

+ info at clean-code-developer.com and here.


1 Comment

Favour composition over inheritance

The 4th principle from the red grade in the clean code development grade system says (from wikipedia):

Composition over inheritance (or Composite Reuse Principle) in object-oriented programming is a technique by which classes may achieve polymorphic behaviour and code reuse by containing other classes that implement the desired functionality instead of through inheritance.

Inheritance is used in object-oriented programming as a way to reuse code through different objects.  We can define parent-children object structures, so methods an variables are passed from the parents to their children Рthe code is inherited. This is a powerful mechanism to avoid code replication Рto be DRY-, but it has its drawbacks.

img73

The problem is that in a parent-children structure, ¬†children are dependent of their parent. If a behaviour in a parent changes all its children’s behaviours will automatically change. Or if a new behaviour is added to the parent all the children will inherit that behaviour too. Sometimes this is not what we really want. Let’s see why.

I am going to use an example from the first chapter of the book head first design patterns.

head_first_design_pattern

In the example, the user wants to build an application which deals with different types of ducks. Every duck flies, swims, and quacks, so in order to reuse those behaviours a Duck super-type is created with the methods quack, swim and fly. Every duck in the system will inherit from the Duck class and therefore inherit those behaviours too.

intialDesign2_itwbm

The problem comes when a new type of duck is introduced into the system which is not supposed to fly: the RubberDuck. If we make this new type to inherit from Duck, we will make the rubber duck fly! That’s wrong.. But if we don’t use inheritance we will have to replicate the quack and swim¬†methods! That’s not really DRY.. So what should we do??

The solution to this is to use¬†composition for the code reuse instead of inheritance.¬†Each of the behaviour that a¬†duck could need -quack, swim, fly – will be separated into a new class –QuackBehaviour, SwimBehavour, FlyBehaviour. Then, each different duck type will use just the needed behaviours.

The code will look like this:

public abstract class Duck
{
 protected IFlyBehavior flyer;
 public virtual void DoFly()
 {
 this.flyer.Fly();
 }

}

public class MallarDuck
{
 public RubberDuck()
 {
 flybehaviour = new DoesntFlyBehaviour();
 }
}

public class RubberDuck
{
 public RubberDuck()
 {
 flybehaviour = new DoesntFlyBehaviour();
 }
}

public interface IFlyBehavior
{
 public void Fly();
}

public class FlyWtihWingsBehaviour: IFlyBehavior
{
 public void Fly()
 {
 // Flying coe
 }
}

public class DoesntFlyBehaviour: IFlyBehavior
{
 public void Fly()
 {
 // Do nothing
 }
}

The example in the book goes deeper and ends up using the Strategy Pattern. I recommend reading that first chapter and the rest of the book if interested. I quite like it, it does not just go about design patterns, but also about main oo principles and why these patterns exist. Also, the first chapter is free in amazon’s look inside or as a sample for the kindle!

In conclusion, inheritance it’s a good way of keeping our code clean and DRY, but it makes sub-classes coupled to their¬†super-classes. Use composition instead ¬†of inheritance if possible.

head_first_design_pattern - Copy

As it says in the book cover, do as Jim and cut down your inheritance! ¬†ūüėČ