Browsing all articles in .NET Tests
Aug
19
Comments

Dependency Injection – Keep your privates to yourself

Author Eli Lopian    Category .NET Tests, TDD     Tags

Jacob Proffitt has hit the nail on the head with his “I do wish that people would admit that DI doesn’t have compelling applicability outside of Unit Testing” post, the discussion continues with Nate Kohari response post and Jacobs counter post. Oren has also joined in with two posts.

Here a some ideas for you to think about.

DI as a Silver Bullet – You lose power

When you use DI as a ’Silver Bullet’ you are losing more then half the abilities of your programming language. You can not use static methods or the ‘new‘ keyword or sealed types. Oh, you have to make all your methods virtual too. This is going to be even harder once Extension Methods (and Linq) become main stream.

Code to Enable Change – Costs More

Creating Code that is there only to “Enable Change” has a big “YAGNI” written all over it. (Making the code more complex and thus wasting time in development and then in maintenance, for a chance that it will be used in the future). We have understood that this is the wrong plan ages ago. We now know that we can not predict the future and it is best to change our code only when we need to (a process called refactoring).

Keep your Privates to Yourself

Jacob, you are quite right about DI coming into fashion only because the tools where not good enough. DI does have other applications outside testing, but it is being overused in most application only to make the code testable.

One of the first issues that was discussed when TDD was starting was: “should we change our code to make it testable?”
Should we change the visibility of our code?
Should we change the design of our code?
This lead to a collision between testable code and OO encapsulation. Developers started to expose private parts of the code to enable testing. It started with private fields and methods and now it is the complete design. This collision still exists when using inadequate tools, but with the right tools, you can enjoy the best of both worlds.

Get the Best Tools to get the Job Done

Thousands of developers have understood this and have started testing there code without being forced to use a specific pattern required by some tools. Many development shops, didn’t test their code because of the testability/design collision. With the right tools they now understand and test their code.

As Joel Says: “Get the best tools

Aug
7
Comments

A New Trick

Author Eli Lopian    Category .NET Tests, TDD     Tags

I have read this post Interaction based testing using TypeMock.

This code:

Mock clientMock = MockManager.Mock(typeof (Client)); clientMock.Strict = true; Client client = new Client();

Is exactly the same as this code:

MockObject<Client> clientMock = MockManager.MockObject<Client>(); Client client = clientMock.Object;

I prefer the latter, the main reason being that using MockObject  ensures that the Object is the one being mocked.

Here is an example that won’t work because we added a new Mock before the previous code:

Mock firstClientMock = MockManager.Mock(typeof (Client)); Mock clientMock = MockManager.Mock(typeof (Client)); clientMock.Strict = true; Client client = new Client(); // this will be contolled by firstClientMock

In this case our client is controlled by the firstClientMock instead of the clientMock. This won’t happen if we use MockObject

Jul
22
Comments

Unit Testing Code with System.Diagnostics.Debug

Author Eli Lopian    Category .NET Tests     Tags

Matt Ellis has answered Ron Cain’s question about Assert in the context of a test harness. I would answer differently.

When testing code that uses Debug.Assert, you would want to fail the test when that Assert fails. Here is a small piece of code that will do it for you (without needing specialized configuration files, this will keep the test confined in the actual test class and not distributed in several places)

// This Class will fail the test when a Debug.Assert has failed public class TestTraceListener:DefaultTraceListener { public override void Fail(string message, string detailMessage) { Assert.Fail("Debug.Assert Failed: "+message+" "+ detailMessage); } } [Test] public void TestCodeWithFailingDebugAssert() { // use special test tracer Trace.Listeners.Remove("Default"); Trace.Listeners.Add(new TestTraceListener()); // see what happens when a Debug.Assert fails // this is normally hidden somewhere deep inside the code Debug.Assert(false); }
Jun
25
Comments

Nicer Tracing with [VerifyMocks]

An unknown feature, (at least till this blog) of the final version of TypeMock 4.0 is the Tracer Utility. Up till this version each time you called MockManager.Init() or when TypeMock started a new sessions the Tracer showed an Initialization (#number) to make it possible to trace the mocked calls.
image

The reason for this was that we just didn’t know that names of the tests. But when using the [VerifyMocks] attributes, we already know the names of the tests and we incorporated this into the Tracer. So using the decorators will make it easier to trace your mocks

image

Notice the names of tests actually appear in the tracer. Cool!

Jun
19
Comments

Good Programming is about Balance

Author Eli Lopian    Category .NET Tests, TDD     Tags

This post hits the nail on its head:
When good programming practices are just too good.

What struck me … is the ridiculous amount of code required to implement simple things.

I love this paragraph

We all love rules – with them, you don’t have to think much, you just apply what the smart guys think is the best. However, lately we younger generation begin rebel and declare these rules as “elitist crap”.

Good programming is an art, and thus good programmers question and think about all aspects of their code. We don’t just follow rules, we invent them.

Jun
11
Comments

Design vs. Process

Author Eli Lopian    Category .NET Tests, TDD     Tags

Oren Eini has posted Tools vs. Design about the Really Simple Dialog post.

It is NOT the design that will give you the freedom to expand and build extendable and maintainable systems. It is impossible to see the future and to implement the best design, that is what YAGNI is about. It is the process that will allow us to meet future requirements. A process that will allow us to change the design as the features grow.

Lets recall the TDD process:

Write Tests -> Code -> Refactor (Design)

Notice that the Design stage is the LAST stage, it is not:

Design (For Testability) -> Test -> Code

Of course we need Tools to support this process, the tools are a testing framework, continuous integration server, and perhaps a mocking framework to allow testing your code no matter what design you chose. We might end up with the same design that Jeremy started with, but we might not. The code might be simple enough to just be there, saving time maintaining the complex MVP code, that many developers are still learning. We do have the option to change this in the future if our code is becoming complex enough to require this.

Using this process we can give our customers business value and shorten the Time To Market, while leaving the option of growth when needed.

I will conclude, a good process is critical to building maintainable, customer value systems, on the other hand shouting out OO Principles will not ensure this

Jun
7
Comments

Extending Test Frameworks

Author Eli Lopian    Category .NET Tests, TDD     Tags

One really nice feature of TypeMock.NET 4.0 is the ability to extend any/all testing frameworks.

Each test framework has (or lacks) its own extension mechanism, making it hard add extension to all the frameworks. With TypeMock we can now write an new test decorator that will work for all frameworks, including vsTest and nunit, and all runner-tools including TestDriven.NET and ReSharper.

Actually, It is possible to decorate and extend ANY method! As long as it is run with TypeMock enabled. So it is now really simple to implement Roys Enterprise Services to do database testing, and Ian’s Even simpler way for ALL testing frameworks, without rewriting the test framework, extending base classes or forcing ALL tests in fixture to rollback.

We will be able to write the following test:

[Test,Rollback] public void Insert() { //Do some inserts into the DB here and automatically roll back }

Here is the code that does it
[UPDATE: Fixed according to Jonas comment]

[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, AllowMultiple = false, Inherited = true)] public class RollbackAttribute : DecoratorAttribute { public override object Execute() { using( new TransactionScope(TransactionScopeOption.RequiresNew)) { // run the test return base.CallDecoratedMethod(); } } }

It is possible to rollback on all tests by decorating the class

[TestFixture,Rollback] public class DatabaseTests { //Do many DB tests here and automatically roll back }

We have implemented the [VerifyMocks] and [ClearMocks] using this technique.

Jun
7
Comments

TypeMock 4.0 released

Author Eli Lopian    Category .NET Tests     Tags

We have fixed most the defects from the beta and have released version 4.0.

Thank you beta users!

May
31
Comments

The Humble Dialog (and famous musketeers)

Author Eli Lopian    Category .NET Tests     Tags

I have read Jeremy’s Build you own CAB series (Build your own CAB Part #2 – The Humble Dialog Box). Jeremy is building the series with the help of  d’Artagnan the famous Musketeer wanna-be.

Due to both his pride and an urge to ingratiate himself with those he wished to join, d’Artagnan is challenged to a duel by three musketeers Athos, Porthos, and Aramis. d’Artagnan had a little surprise for his opponents. He did not divide his concerns, instead he embraced them, and found himself fighting all 3 together. The 3 started fighting with each other over who will fight d’Artagnan first, but they all ended up fighting Cardinal Richelieu’s guards, who threaten to arrest them because duels are forbidden by royal decree…

I am going to show you just how we can manage to unit test a Simple Dialog without separating concerns and overcome the forbidden decree that GUI is hard to test.

I will use Jeremy’s requirement:

If the user attempts to close the XYZ screen without saving any outstanding changes, a message box is displayed to warn the user that they are discarding changes.  If the user wishes to retain the outstanding work, do not close the screen.  The message box should not be shown if the data has not been changed.

private void SimpleForm_FormClosing(object sender, FormClosingEventArgs e)

{

    if (isDirty())

    {

        bool canClose = MessageBox.Show(“Ok to discard changes or cancel to keep working”, “Confirm”,MessageBoxButtons.OKCancel) == DialogResult.OK;

        e.Cancel = !canClose;

    }

Unlike Jeremy, MessageBox will be no problem at all to test, actually the tests are quite straight forward and will give you the developer the freedom to choose (and refactor) the code when needed.

Here are the tests:

[Test]
[VerifyMocks]
public void CloseTheScreenWhenTheScreenIsNotDirty()

{

    SimpleForm testedDialog = new SimpleForm();

 

    using (RecordExpectations record = RecorderManager.StartRecording())

    {

        testedDialog.isDirty(); // mocked

        record.Return(false).RepeatAlways();

    }

    testedDialog.Show();

    testedDialog.Close();

    Assert.AreEqual(false, testedDialog.Visible);

}

 

[Test]

[VerifyMocks]

public void CloseTheScreenWhenTheScreenIsDirtyAndTheUserDecidesToDiscardTheChanges()

{

    SimpleForm testedDialog = new SimpleForm();

 

    using (RecordExpectations record = RecorderManager.StartRecording())

    {

        testedDialog.isDirty(); // mocked

        record.Return(true).RepeatAlways();

        MessageBox.Show(“whatever”); // mocked

        record.Return(DialogResult.OK);

    }

    testedDialog.Show();

    testedDialog.Close();

    Assert.AreEqual(false, testedDialog.Visible);

}

 

[Test]

[VerifyMocks]

public void CloseTheScreenWhenTheScreenIsDirtyAndTheUserDecidesNOTToDiscardTheChanges()

{

    SimpleForm testedDialog = new SimpleForm();

 

    using (RecordExpectations record = RecorderManager.StartRecording())

    {

        testedDialog.isDirty(); // mocked

        record.Return(true).RepeatAlways();

        MessageBox.Show(“whatever”); // mocked

        record.Return(DialogResult.Cancel);

    }

    testedDialog.Show();

    testedDialog.Close();

    Assert.AreEqual(true, testedDialog.Visible);

}

Cool Ah!, we mocked the unmockable MessageBox, we also mocked the SimpleForm.isDirty, we actually tested the logic that we needed, this makes the GUI very testable with no effort at all.

The mocking is done in the using block where all calls are mocked and the behavior is set. Verification that the expectations where called is done using the [VerifyMocks] attribute. We could also test the message that is being displayed on the message box, but that is another test.

You should of course separate the GUI class when it grows bigger, but your test will still pass even if you do separate the concerns! Unless you change the message box to one of your own, but you have the ability to really do Just In Time Design (YAGNI)

Just one more tip for those of you who will try this technique. It will be a good idea to mock MessageBox.Show in all cases, just in case the test fails-> we don?t want the tests to hang with the message box. Just use .RepeatAll or FailIfCalled to make sure that we don’t fail if the MessageBox is not shown.

May
16
Comments

Released TypeMock 4.0 Beta

Author Eli Lopian    Category .NET Tests     Tags

We have released a beta version of TypeMock 4.0, this should be a really stable version. We intend to release the final version within 2 weeks.

There is a lot of new stuff in this version. you can read about it in the Release Notes.

Some nice stuff are:

The new TypeMock Decorators.

Using these decorators will work for All test frameworks and will automatically verify mocks

[Test] [VerifyMocks(Timeout=150)] // mocks are always verified public void TestVerificationWithTimeout() { // setup mocks // run tests // optional assert Assert.That(): }

Generic Reflective API

Use generic to create reflective mocks.

[Test] [VerifyMocks] // mocks are always verified public void Test() { Mock mockControl = MockManager.Mock<ClassToMock>(); new ClassToMock(); // This is mocked }

Intelligent Natural Mocks

When creating a mocked return value, within a recording block, TypeMock.NET will not mock the return value

using (RecordExpectations recorder = RecorderManager.StartRecording()) { MockedType.CallAMethod(); recorder.Return(new SomeReturnType(1,2));// SomeReturnType is NOT mocked }