Mocking the context of application

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?

3

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

} 

7

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.

Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa Dịch vụ tổ chức sự kiện 5 sao Thông tin về chúng tôi Dịch vụ sinh nhật bé trai Dịch vụ sinh nhật bé gái Sự kiện trọn gói Các tiết mục giải trí Dịch vụ bổ trợ Tiệc cưới sang trọng Dịch vụ khai trương Tư vấn tổ chức sự kiện Hình ảnh sự kiện Cập nhật tin tức Liên hệ ngay Thuê chú hề chuyên nghiệp Tiệc tất niên cho công ty Trang trí tiệc cuối năm Tiệc tất niên độc đáo Sinh nhật bé Hải Đăng Sinh nhật đáng yêu bé Khánh Vân Sinh nhật sang trọng Bích Ngân Tiệc sinh nhật bé Thanh Trang Dịch vụ ông già Noel Xiếc thú vui nhộn Biểu diễn xiếc quay đĩa Dịch vụ tổ chức tiệc uy tín Khám phá dịch vụ của chúng tôi Tiệc sinh nhật cho bé trai Trang trí tiệc cho bé gái Gói sự kiện chuyên nghiệp Chương trình giải trí hấp dẫn Dịch vụ hỗ trợ sự kiện Trang trí tiệc cưới đẹp Khởi đầu thành công với khai trương Chuyên gia tư vấn sự kiện Xem ảnh các sự kiện đẹp Tin mới về sự kiện Kết nối với đội ngũ chuyên gia Chú hề vui nhộn cho tiệc sinh nhật Ý tưởng tiệc cuối năm Tất niên độc đáo Trang trí tiệc hiện đại Tổ chức sinh nhật cho Hải Đăng Sinh nhật độc quyền Khánh Vân Phong cách tiệc Bích Ngân Trang trí tiệc bé Thanh Trang Thuê dịch vụ ông già Noel chuyên nghiệp Xem xiếc khỉ đặc sắc Xiếc quay đĩa thú vị
Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa
Thiết kế website Thiết kế website Thiết kế website Cách kháng tài khoản quảng cáo Mua bán Fanpage Facebook Dịch vụ SEO Tổ chức sinh nhật