it is correct to use setup in unit test C#

1.7k Views Asked by At

I am explaining better, I am studying how to do unit tests in C # with NUnit and justmock. I am reading the book the art of unit tests, Here I am told that whenever possible try to avoid [SetUp] for a previous scenario configuration a try. But googling me on blog that if it's good to use these settings in [SetUp], I'm really confused, I am aware that if the scenario is very large, the arrange of my test method grows and I have to rafactorizar, Entonce the best elaborate question would be, When using [SetUp] or if there is some type of pattern when the scenario to test is very large and the Arrange code is affected by this, helpmee???

for example:

[TestMethod]
    [Owner("Joaquin")]
    public void Update_CorrectViewDtoAndAllowedUser_ReturnsTrue()
    {
        // Arrange
        const string userName = "johndoe";
        var viewDto = new ViewDto { Id = 1 };
        var view = new View { Id = 1 };

        var authorizationService = Mock.Create<IAuthorizationService>();
        Mock.Arrange(() => authorizationService.GetAccessLevel(viewDto.Id,userName))
            .Returns(AccessLevel.ReadWrite);

        var mapper = Mock.Create<ITypeMapperService>();
        Mock.Arrange(() => mapper.Map<View>(Arg.Is(viewDto)))
            .Returns(view);

        var viewService = Mock.Create<IViewService>();
        Mock.Arrange(() => viewService.GetById(view.Id))
            .Returns(view);

        var viewAppService = CreateViewAppService(viewService, authorizationService, mapper);

        // Act
        var result = viewAppService.Update(viewDto, userName);

        // Assert
        Assert.IsTrue(result);
    }

Here my arrange is very extensive and I would not want to remove it for a private method or pass it to the [SetUp] there is no pattern to solve this in another way

1

There are 1 best solutions below

0
On

The main problem with SetUp is, that NUnit uses one instance of a TestFixture for all tests in it. Changes to the state will be available to all unit tests.

The main problem is, that unit tests have no execution order. The leftover state could break the following unit tests. Errors like that are extremely hard to find. (and may depend on your test environment. Your build server can get different test results, then your local machine).

The usage SetUp is no problem, as long you reset all changed state in TearDown.

Another alternative is to use XUnit, which does not use the same instance for all tests. The SetUp is done in the constructor, and because the class is not reused, no cleanup is needed.

EDIT: But as you stated you are reading "The art of unit testing". The book has nearly a complete chapter on this problem. And will probably explain this a lot better than me ;)