Site icon R-bloggers

3 Essential Types of Unit Tests Every R Developer Should Know

[This article was first published on jakub::sobolewski, and kindly contributed to R-bloggers]. (You can report issue about the content on this page here)
Want to share your content on R-bloggers? click here if you have a blog, or here if you don't.

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

To leave a comment for the author, please follow the link and comment on their blog: jakub::sobolewski.

R-bloggers.com offers daily e-mail updates about R news and tutorials about learning R and many other topics. Click here if you're looking to post or find an R/data-science job.
Want to share your content on R-bloggers? click here if you have a blog, or here if you don't.
Exit mobile version