Ad space (banner)
๐Ÿ“ŠR Lessons
Lesson 28 / 68

Checking correctness with stopifnot (a first step towards testing)

This lesson covers writing a simple test with R's stopifnot, with the aim of taking the first step towards checking your program is correct.

stopifnot(condition) raises an error and stops when the condition is FALSE. Checking automatically that a function's result is what you expected is the basic idea behind test code.

The sample code checks with an if statement whether add(2, 3) gives 5, printing a pass or a fail accordingly. It gives you a feel for confirming a result in code rather than by eye.

A common early stumble is checking behaviour by hand every time and missing something. In practice you would use a dedicated framework (such as testthat), but the underlying idea is the same.

Remember too that an assertion is a development-time debugging aid, not a substitute for real error handling in production.

๐Ÿ“– Reference code
โœ๏ธ Your code
Type your code, then press "Run"

๐Ÿงช This site can't compile or run R directly, so it checks on the spot whether what you typed matches the reference code (scoring happens entirely in your browser โ€” nothing is sent anywhere).

Ad space (banner)
Ad space (in-article)