tests/testthat/test_mockable.R

library(mockable)

testthat::context("Mockable functions")

testthat::test_that(
  "Mockable function initialisation",
  {
    f <- function(a) a^2
    g %mockable% f
    testthat::expect_is(g, 'MockableFunction')
    testthat::expect_equal(g(1), 1)
    testthat::expect_equal(g(5), 25)
  }
)

testthat::test_that(
  "Mockable function mocking",
  {
    f <- function(a) a^2
    g %mockable% f
    testthat::expect_is(g, 'MockableFunction')
    testthat::expect_equal(g(5), 25)
    f <- function(a) a+7
    testthat::expect_equal(g(3), 9)
    g %mock% f
    testthat::expect_is(g, 'MockableFunction')
    testthat::expect_false(g(5) == 25)
    testthat::expect_equal(g(2), 9)
    testthat::expect_equal(g(4), 11)
  }
)

testthat::test_that(
  "Mockable function unmocking",
  {
    f <- function(a) a^2
    g %mockable% f
    testthat::expect_equal(g(5), 25)
    f <- function(a) a * 3
    g %mock% f
    testthat::expect_equal(g(5), 15)
    testthat::expect_equal(g(4), 12)
    unmock(g)
    testthat::expect_equal(g(4), 16)
  }
)


testthat::test_that(
  "Mockable function pass by reference",
  {
    f <- function(a) a^2
    g %mockable% f
    testthat::expect_is(g, 'MockableFunction')
    testthat::expect_equal(g(5), 25)
    h <- g
    testthat::expect_is(h, 'MockableFunction')
    testthat::expect_equal(h(5), 25)
    f <- function(a) a + 6
    g %mock% f
    testthat::expect_equal(g(5), 11)
    testthat::expect_equal(h(5), 11)
    unmock(h)
    testthat::expect_equal(g(5), 25)
    testthat::expect_equal(h(5), 25)

  }
)

testthat::test_that(
  "Mockable function definition",
  {
    f <- function(a) a^2
    g %mockable% f
    testthat::expect_is(g, 'MockableFunction')
    testthat::expect_equal(g(5), 25)
    f1 <- definition(g)
    testthat::expect_is(f1, 'function')
    testthat::expect_equal(f, f1)
    testthat::expect_equal(f1(5), 25)
    f <- function(a) a - 7
    g %mock% f
    testthat::expect_equal(g(10), 3)
    testthat::expect_equal(f1(5), 25)
    f1 <- definition(g)
    testthat::expect_equal(f1(10), 3)
  }
)
EntirelyDS/mockable documentation built on May 6, 2019, 3:48 p.m.