3 Types of Unit Tests Everyone Should Know

3 min read

When approaching to write a unit test, we might ask ourselves:

Getting answers to these questions helps overcome writer’s block.

To make it easier to think about what to test and to make a more informed decision on how we need to test it, we may categorize tests into:

Let’s see in what circumstances should each type be used.

Direct Response Tests

Example

describe("Stack", {
  it("should return the last pushed value when popping an item", {
    # Arrange
    my_stack <- Stack$new()
    my_stack$push(1)

    # Act
    value <- my_stack$pop()

    # Assert
    expect_equal(value, 1)
  })
})

Tips

State Change Tests

Example

describe("Stack", {
  it("should not be empty after pushing an item", {
    # Arrange
    my_stack <- Stack$new()

    # Act
    my_stack$push(1)

    # Assert
    expect_false(my_stack$empty())
	})
})

Tips

Interaction Tests

Example

describe("Stack", {
  it("should log what item has been pushed", {
    # Arrange
    logger <- mockery::mock()
    my_stack <- Stack$new(logger)

    # Act
    my_stack$push(1)

    # Assert
    mockery::expect_args(
      logger,
      n = 1,
      "Pushed 1 onto the stack"
    )
  })
})

Tips