1

We have a context of the application which is a static class named Holder containing several static properties initialized by objects that are used throughout the application.

All over the unit tests we need to initialize the context by mocks. In the current implementation, the context defense itself from reinitializing, so it contains Singletons. Because of that all tests share mocks, hence they take a responsibility to correctly clear them, I mean to clear their's behaviour.

What do you think about is it normally to have such a shared state between unit tests? And if you consider that as a bad practice, than I'll be appreciated for some advices.

Update. I'm sorry for misleading. One of the most important thing to mention is that I can't recreate many times the inner state of the Holder class. What options do I have in such a case?

  • 4
    If your code is hard to test, you shouldn't try to fix testing problems, you should fix your code first. – Thomas Junk Nov 13 '14 at 11:12
  • 2
    The correct answer is to remove that static Holder class. The barely acceptable answer is to use a Fakes shim for the static values. – SHODAN Nov 13 '14 at 12:28
  • Relevant literature: Working Effectively with Legacy Code. – Mark Seemann Dec 16 '14 at 8:01
4

I had a similar problem with my code with global state via singelton.

As @Thomas-Junk-s and @SHODAN-s comment suggested i refactored my code to make the static global state non-static through constructor Dependency injection.

Example

original code

public static class Global {
    public static int getSomeGlobalState() {...}
}

public class MyClass {
    public MyClass(...) {...}

    public myFunction(....) {
        ....
        int i = Global.getSomeGlobalState()
        ....
    }
}

refactored static global method to nonstatic global method

public class Global {
    private Global global = new Global();

    // singelton to keep old code compatible
    public static Global getGlobal() {return global;}

    // not static anymore
    public int getSomeGlobalState() {...}
}

public class MyClass {
    public MyClass(...) {...}

    public myFunction(....) {
        ....
        // replacing call to static member Global.getSomeGlobalState()
        int i = Global.getGlobal().getSomeGlobalState()
        ....
    }
}

refactored removed depency to static class Global from method myFunction to constructor

public class MyClass {
    Global global;

    // depricated constructor compatible with old api.
    public MyClass(...) {this(..., ...;Global.getGlobal());}

    // new constructor to be used in future
    public MyClass(..., Global global) {...;this.global=global;}

    public myFunction(....) {
        ....
        int i = global.getSomeGlobalState()
        ....
    }
}   

after introducing a di-container: refactored to replace static singelton class Gloal to container

public class Global {
    public Global() {...}

    public int getSomeGlobalState() {...}
}

public class MyClass {
    public MyClass(..., Global global) {...;this.global=global;}

    public myFunction(....) {
        ....
        int i = global.getSomeGlobalState()
        ....
    }
}   

Each refactoring made shure that the code, that ueses MyClass needs no modification.

In the last refactoring i added a di-container that is responsible for creating a singelton Global-Class and that injects the global instance into its customers like MyClass this way the old MyClass constructor could be removed.

[update 2014-12-11]

if you donot want to add a dependency all over the codebase as your comment suggests you can onmit the last refactoring step:

public class MyClass {
    // constructor used in consuming classes.
    public MyClass(...) {this(..., ...;Global.getGlobal());}

    // constructor used for unittests where you can replace global.
    public MyClass(..., Global global) {...;this.global=global;}

} 
  • 2
    +1. Singletons make reusing objects that depend on them in different ways difficult to achieve. Testing is such a different way, and is the most obvious reason to refactor to dependency injection, but it is by no means the only one. You'll benefit in general increased flexibility of your code, too. – Jules Nov 13 '14 at 13:17
  • I see. The problem with this approach is that I have to add a dependency all over the codebase. I don't what to add the same dependency just everywhere. That's why exactly it was implemented as a static class. – EngineerSpock Dec 11 '14 at 6:59
  • @Engineer Spock: i have updated my answer – k3b Dec 11 '14 at 8:56
  • And how does it differentiate from the simple static object? How would I set the context from my unit tests? By the way, I can't just make the inners of the context injectable, because they have to be set dynamically somewhere at the start of the application, not from the IoC container. – EngineerSpock Dec 11 '14 at 11:07
  • +1 although I'd use Pure DI instead of a DI Container. – Mark Seemann Dec 15 '14 at 14:48
0

Yes, it's better not to share state between unit-tests, and have them independent from each other. But it doesn't mean that you can't share code between unit-tests.

For example(using NUnit + FluentAssertions + FakeItEasy):

    [TestFixture]
    [Category("Unit")]
    public class when_rolling_back_unit_of_work : UnitOfWorkScenario
    {
        [Test]
        public void should_rollback_and_dispose()
        {
            //act
            UnitOfWork.Do(uow => uow.Rollback());

            //assert
            A.CallTo(() => SessionScope.Commit()).MustNotHaveHappened();
            A.CallTo(() => SessionScope.Rollback()).MustHaveHappened(Repeated.Exactly.Once);
            A.CallTo(() => SessionScope.Dispose()).MustHaveHappened(Repeated.Exactly.Once);
        }
    }

In the example above, we derive our test from UnitOfWorkScenario class which shares common initialization logic between our tests for UnitOfWork.

This class looks like:

public class UnitOfWorkScenario
    {
        protected ISessionScopeFactory SessionScopeFactory { get; set; }
        protected ISessionScope SessionScope { get; set; }
        public UnitOfWorkScenario()
        {
            SessionScopeFactory = A.Fake<ISessionScopeFactory>();
            SessionScope = A.Fake<ISessionScope>();
            A.CallTo(() => SessionScopeFactory.Open()).Returns(SessionScope);
            Func<string, ISessionScopeFactory> sessionScopeFactoryExtractor = name => (name == UnitOfWorkSettings.Default.StorageName ? SessionScopeFactory : null);
            UnitOfWork.SessionScopeFactoryExtractor = sessionScopeFactoryExtractor;
        }
    }

The point is that you could share common initialization logic between your tests, at the same time keeping them independent from each other. Nevertheless, if you need to clean-up something(static property as an example), you could do it in base class constructor, or use features of your unit-test framework(e.g. method with TearDown attribute in NUnit) to do it, BUT specifying this logic in the only one place in your base class.

Sorry if I misunderstood your question a bit.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.