F
F
F10002021-04-28 21:07:17
C++ / C#
F1000, 2021-04-28 21:07:17

Creating an object under test in the constructor of a unit test class?

Hello. There is a method that creates a collection of objects from an incoming string. If, during unit testing, we get a collection and store it in the constructor, and in test methods only call asserts that check objects in the collection, will this be considered bad practice?

public class Test
  {
    private List<T> collection;

    public Test()
    {
      collection = Foo("const"); // тестируемая функция
    }
        

    [Fact]
    public void CollectionIsNotNull()
    {
      Assert.NotNull(collection);
    }    
    // остальные тесты
  }

Answer the question

In order to leave comments, you need to log in

1 answer(s)
U
user_of_toster, 2021-04-29
@F1000

In js/ts, there is a similar practice, when in the beforeAll() block, the components necessary for tests related by concept are set, and then the tests themselves come out in one or two lines and consist only of asserts. IMHO, it helps to comply with DRY and there is nothing wrong with that

describe("My class", () => {
     let myMock, myFunc, myClass;
     beforeAll(() => {
         /// здесь устанавливаю моки, впрыскиваю зависимости и т.д;
     })

     test("mock works well with numbers", () => {
          assert(myMock).worksWellwithStrings()
     })

     test("class works well with numbers", () => {
          assert(myClass).worksWellWithMocks()
     })

     test("instance works well with numbers", () => {
          assert(myInstance).worksWell()
     })
})

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question