<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Jakub Sobolewski on Medium]]></title>
        <description><![CDATA[Stories by Jakub Sobolewski on Medium]]></description>
        <link>https://medium.com/@jakubsobolewski?source=rss-7222fc8ef8b8------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*tRDpqb52hj5rfmkVWhOBuw.jpeg</url>
            <title>Stories by Jakub Sobolewski on Medium</title>
            <link>https://medium.com/@jakubsobolewski?source=rss-7222fc8ef8b8------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 05 Dec 2026 14:52:57 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@jakubsobolewski/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[2 Paths Of Automated Testing]]></title>
            <link>https://jakubsobolewski.medium.com/2-paths-of-automated-testing-b8b0eee86610?source=rss-7222fc8ef8b8------2</link>
            <guid isPermaLink="false">https://medium.com/p/b8b0eee86610</guid>
            <category><![CDATA[unit-testing]]></category>
            <category><![CDATA[testing]]></category>
            <category><![CDATA[rstats]]></category>
            <dc:creator><![CDATA[Jakub Sobolewski]]></dc:creator>
            <pubDate>Mon, 06 Jan 2025 19:59:49 GMT</pubDate>
            <atom:updated>2025-01-06T19:59:49.227Z</atom:updated>
            <content:encoded><![CDATA[<p>Introduction of automated testing has its costs. It takes time to learn testing, it takes time to write and maintain tests.</p><p>We need to be aware of those costs.</p><p>It might be tempting to skip on testing in the early stages of the project, but it might be a costly mistake.</p><p>Development without testing might be faster at the beginning, but as the project goes on, there should be a point when the initial investment of writing tests starts to pay off.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*iJAw6c2kE8T80lY1.png" /></figure><p>We have built good tests when the additional cost of building and maintaining automated tests is offset by savings through reduced manual testing. It should be offset by savings on debugging, troubleshooting and the cost of fixing the defects that would have gone undetected until the early production usage of the software.</p><p>To have good tests we need to:</p><ul><li>Find the right tests for coverage. We don’t need to test everything. Test only what we need from the system.</li><li>Have resources for testing. Testing is an investment in quality that pays off in the long run.</li><li>Ensure our tests are fast. If we need to wait for a long time for the feedback from tests, we will not run them often.</li><li>Make tests predictable. We need both tests and the test environment to be deterministic to not troubleshooting them often.</li><li>Prioritize testing. If we write them first, we’ll never “run out of time” to write them.</li></ul><p>When we managed to build good tests we can channel our resources away from manual testing to delivering value.</p><p>Whether we succeeded in writing good tests might be discovered only on the later stages of the project, when the test suite becomes large enough.</p><p>If we were unsuccessful, tests become a burden, and can halt the development process as changing the production code requires changing a ton of tests.</p><p>If tests become too difficult or time consuming to maintain, it’s easy to give up on adding them. We might be even tempted to remove some of the test code as it’s not possible to change it.</p><p>This situation is dangerous and it slowly creeps in, it might be hard to notice it early, but there are heuristics that can help us see and avoid it, like the <a href="https://www.martinfowler.com/articles/practical-test-pyramid.html">Testing Pyramid</a> and separation of concerns.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6k-1CQhWkD4BiLMDxFVB9w.png" /><figcaption>Manual testing vs bad automated testing</figcaption></figure><p>To avoid this situation we need to focus on:</p><ul><li>Testing what we need from the system. Don’t test every combination of inputs.</li><li>Testing only public interfaces of our code. Then we can be more confident we don’t test implementation details that make our tests brittle.</li><li>Writing fast tests. If a specification of our system can be asserted in a focused, fast unit test, do it with a unit test, not E2E or acceptance test.</li></ul><p>Don’t let tests get in your way of delivering great software, use them to build your code faster and with better confidence.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b8b0eee86610" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Want To Get Even Faster Feedback From Your Unit Tests? Optimize Your Test Files Structure.]]></title>
            <link>https://blog.devgenius.io/want-to-get-even-faster-feedback-from-your-unit-tests-optimize-your-test-files-structure-4038335601bc?source=rss-7222fc8ef8b8------2</link>
            <guid isPermaLink="false">https://medium.com/p/4038335601bc</guid>
            <category><![CDATA[rstats]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[unit-testing]]></category>
            <dc:creator><![CDATA[Jakub Sobolewski]]></dc:creator>
            <pubDate>Sat, 23 Nov 2024 15:48:04 GMT</pubDate>
            <atom:updated>2024-11-23T15:48:04.313Z</atom:updated>
            <content:encoded><![CDATA[<p>When using tests as a mechanism of getting feedback on the code we write, it’s critical to get it as fast as possible.</p><p>How useful a test is if we need to wait a minute to see if the code we wrote works as expected after every change? Even if this feedback comes after only 10 seconds, if we multiply by the number of changes we make, it amounts to a lot of time lost waiting for tests to finish running. The time extends as we add more and more tests.</p><p>Optimising the code itself has its limits and is difficult, but we can optimise test structure itself to get the feedback faster.</p><h3>Leverage testthat::test_file to run a single test file.</h3><p>Let’s imagine we have a file that contains multiple plot functions R/plots.R.</p><p>We can run it with testthat::test_file(&quot;tests/testthat/plots.R&quot;) to only run tests for our plotting functions. This should already yield significant speedup compared to running all tests with testthat::test_dir(&quot;tests/testthat&quot;) (or with devtools::test()).</p><p>But what if we have a lot of plotting functions and tests? Then running even a single file can take a while.</p><h3>Split test files into smaller ones.</h3><p>To speed the process up, we can split the test suite into smaller chunks.</p><p>We can split our tests/testthat/test-plots.R into:</p><ul><li>tests/testthat/test-plots-barchart.R</li><li>tests/testthat/test-plots-boxplot.R</li><li>tests/testthat/test-plots-scatter.R</li></ul><p>Then we can run tests only for a selected function with testthat::test_file(&quot;tests/testthat/test-plots-barchart.R&quot;).</p><p>When we’re adding a new function or modify an existing one we often don’t need the feedback from the rest of the test files immediately. We can work on this function in isolation, until it meets all requirements and check integration with the rest of the codebase at a later stage.</p><h3>Run segments of tests.</h3><p>If we organize our test files into smaller ones with consistent prefixes we can still run bigger parts of our testing suite in isolation.</p><p>Leveraging the filter argument we can run all plot function tests with testthat::test_dir(&quot;tests/testthat&quot;, filter = &quot;plots&quot;). It’ll run all files that contain &quot;plot&quot; in their name.</p><p>To save ourselves some additional typing we can set up a helper function:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/0*vOHATfS9zX3lnz-N.png" /></figure><p>and put it in .Rprofile so that it’s always available in the environment.</p><h3>Obtain fine control of what you want to run.</h3><p>Now we can just type:</p><ul><li>.test(&quot;barchart&quot;) to run test for a single function and get super fast feedback,</li><li>.test(&quot;plots&quot;) to run tests for a bigger code surface, for example to see how things integrate within a specific domain, or</li><li>.test() to run all tests,</li></ul><p>and get feedback on precisely what we want to check.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4038335601bc" width="1" height="1" alt=""><hr><p><a href="https://blog.devgenius.io/want-to-get-even-faster-feedback-from-your-unit-tests-optimize-your-test-files-structure-4038335601bc">Want To Get Even Faster Feedback From Your Unit Tests? Optimize Your Test Files Structure.</a> was originally published in <a href="https://blog.devgenius.io/">Dev Genius</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[3 Things Tests Can Tell You About Your Code]]></title>
            <link>https://blog.devgenius.io/3-things-tests-can-tell-you-about-your-code-3677573b3d05?source=rss-7222fc8ef8b8------2</link>
            <guid isPermaLink="false">https://medium.com/p/3677573b3d05</guid>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[rstats]]></category>
            <category><![CDATA[unit-testing]]></category>
            <category><![CDATA[unittest]]></category>
            <category><![CDATA[software-development]]></category>
            <dc:creator><![CDATA[Jakub Sobolewski]]></dc:creator>
            <pubDate>Mon, 11 Nov 2024 20:21:59 GMT</pubDate>
            <atom:updated>2024-11-11T20:21:59.662Z</atom:updated>
            <content:encoded><![CDATA[<p>Testing is all about feedback, not only about catching bugs.</p><p>Tests are users of our code. They interact with our code in the same way as users do. They call functions, pass arguments, and expect results. They can tell us a lot about the design of our code.</p><p>But to improve it, we need to pay attention.</p><h3>Tests can tell us if our code is not modular.</h3><p>Modularity is about how easy it is to use a piece of code in different contexts.</p><p>If we run code only in production we run it in one context. If we test it, we run it in another context. If we can’t easily run code in tests, it’s a sign that it will be difficult to use it in any other context.</p><p>If we need to:</p><ul><li>pass a ton of arguments,</li><li>setup a global environment,</li><li>write files to disk,</li><li>or mock a lot.</li></ul><p>It might be a sign that our code is not modular.</p><h3>❌ A dependency on global variables</h3><p>Let’s consider a function that uses a global variable TAX_RATE to calculate the total price of items.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/886/0*0a-k_gglW-T-3avS.png" /></figure><p>In order to test the function, we need to set up a global variable. This makes the test setup more complex and the test harder to understand. It also poses a risk of changing the global state and affecting other tests if we don’t tear down the environment properly.</p><p>Let’s consider the alternative.</p><h3>✅ Dependency injection</h3><p>Instead of relying on a global variable, we can pass the tax rate as an argument.</p><p>It makes the test code simpler and easier to understand, as we can explicitly see what the function needs.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/886/0*blI6e3bkxN90QSKS.png" /></figure><p>Now it doesn’t matter where the tax rate comes from. It can be a global variable, a configuration file, or a database. Testing promotes dependency injection, thus allows easier substitution of components and better flexibility in arranging pieces of code.</p><p>Aiming for simple tests helps make the code modular.</p><h3>Tests can tell us if our code is tightly coupled.</h3><p>Coupling is about interdependence between different parts of the code.</p><p>If we need an extensive setup to run a test (or if it’s nearly impossible to test it), it’s a sign that our code is tightly coupled. Coupling can be easily spotted if we need to stub (substitute) parts of the tested code.</p><p>This is a dangerous situation, because then tests expose implementation details.</p><h3>❌ Tight coupling</h3><p>The calculate_total function uses a get_tax_rate function to calculate the total price of items. We don’t know where the tax rate comes from, but we know that it’s used in the calculation.</p><p>If the implementation of get_tax_rate uses an external dependency that is not available in tests (e.g., a database), we need to stub it.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/886/0*kfJF1UfIALoVxZKH.png" /></figure><p>A change as simple as renaming get_tax_rate will break the test. This is a sign that the test is coupled to the implementation details of the tested code. Now not only the implementation has tight coupling, but so has the test.</p><p>Let’s consider the alternative.</p><h3>✅ Dependency injection</h3><p>If we pass the tax rate as an argument, we don’t need to stub the get_tax_rate function. The code that gets the tax rate is decoupled from the code that calculates the total price.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/886/0*McfpVddwSOLoBNRk.png" /></figure><h3>Tests can tell us if our code does too much.</h3><p>Separation of concerns is about dividing a program into distinct sections, such that each section addresses a separate concern.</p><p>If we need to test too many things in one test, it’s a sign that our code does too much.</p><p>The easiest way to spot it is to look for:</p><ul><li>number of assertions in a test,</li><li>use of and in test titles,</li><li>or a need to set up a lot of things to run a test.</li></ul><h3>❌ Doing too much at once</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/841/0*ZfMgNtRkCBzHB_pa.png" /></figure><p>Instead of doing both behaviors at once, we could refactor the function so that one function calculates the total, the other inserts data into the database.</p><h3>Tests can help us improve the design of our code.</h3><p>Paying attention to feedback from tests can tell us if our code is modular, if it’s tightly coupled, or if it has poor separation of concerns.</p><p>While testing after writing the production code is useful, the feedback from tests can be even more valuable if we write tests first. This is the idea behind Test-Driven Development (TDD).</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3677573b3d05" width="1" height="1" alt=""><hr><p><a href="https://blog.devgenius.io/3-things-tests-can-tell-you-about-your-code-3677573b3d05">3 Things Tests Can Tell You About Your Code</a> was originally published in <a href="https://blog.devgenius.io/">Dev Genius</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[3 Lessons learned from 3 years of testing as an R developer]]></title>
            <link>https://jakubsobolewski.medium.com/3-lessons-learned-from-3-years-of-testing-as-an-r-developer-e8b557b89198?source=rss-7222fc8ef8b8------2</link>
            <guid isPermaLink="false">https://medium.com/p/e8b557b89198</guid>
            <category><![CDATA[unit-testing]]></category>
            <category><![CDATA[rstats]]></category>
            <category><![CDATA[r]]></category>
            <dc:creator><![CDATA[Jakub Sobolewski]]></dc:creator>
            <pubDate>Mon, 21 Oct 2024 07:31:38 GMT</pubDate>
            <atom:updated>2024-10-21T07:31:38.320Z</atom:updated>
            <content:encoded><![CDATA[<p>When I first started working as an R developer, I knew nothing about testing.</p><p>My practice of developing R code was to write some, execute it manually in the console, and see if it worked. The idea of running and checking the same code automatically was absolutely foreign to me.</p><p>How could I develop code if I haven’t run it myself?</p><p>Thankfully I was introduced to the concept of testing by my colleagues and after a few years of practice, here’s what I learned.</p><h3>Eliminate the friction and just start testing.</h3><p>When I first started writing tests, I was overwhelmed by the concept.</p><ul><li>Where should I even start?</li><li>What should I test?</li><li>How should I test it?</li></ul><p>The advice I was given was to think of each test as a process consisting of three steps:</p><ul><li>setup,</li><li>execution,</li><li>and assertion.</li></ul><p>Instead of feeling stuck, and dwelling on possibilities, I could start from an empty test with 3 comments</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/952/1*BiiAG0OrZaVjEfXolO7e7A.png" /></figure><p>and start filling in the blanks.</p><p>Those comments break down the empty space into smaller, more manageable pieces. It’s a recipe that you can follow to create any test. It not only reduces the mental friction, but also makes tests more understandable and maintainable. This approach helps us keep each test focused on a single thing and not dependent on external dependencies. It helps us create tests that are independent units.</p><p>If you’re still confused, start from filling in the part that you know the most about.</p><p>If you add tests after a piece of code is written, you might start from the #Act section as you’ve already seen how the code is called somewhere else and then you can find out how you need to set up the environment to run it.</p><p>If you add tests before writing the code, you might start from the #Arrange and #Assert sections as you might know that given these inputs you expect that output. Then you can start thinking about the interface of the code you will implement to achieve that.</p><h3>Make tests document what you implement.</h3><p>My first tests I’ve ever written looked like <a href="https://github.com/jakubsob/functiondepends/blob/master/tests/testthat/tests-find-functions.R">this</a>:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*bvUzBEhUI7hCroEFS6X-DQ.png" /></figure><p>Looking back at it after a few years it took me a while to understand what I meant to test here…</p><p>If it were a week after I wrote it, it would still require me to read the code to understand what I was testing.</p><p>The most obvious deliverable of tests is the feedback if the code works or not. But the other important aspect is that it can document what the code does. Tests are a communication tool between you and the future you or someone else who will read the code.</p><p>Focus on structuring tests in a way that communicates the intent of the code:</p><ol><li>Use meaningful test titles to describe what the code does.</li><li>Use #Arrange, #Act, #Assert comments to structure the test code.</li></ol><p>Adding a bit of extra effort can significantly increase the value of tests.</p><h3>Focus on the tests that matter.</h3><p>Instead of trying to test everything, focus on the tests that give you the most confidence in the code. We’re not in a competition of having the highest code coverage, we’re chasing a trade off of confidence and development speed. The higher the coverage, the higher the chance that if you change something in the code, you’ll break some tests.</p><p>I tend to skip on testing individual, low-level helper functions if they’re only used in a few places. I trust that if the higher-level functions are working, the lower-level ones are too.</p><p>I focus my efforts on testing the higher-level functions and the edge cases that are most likely to break. This way I can spend more time on testing functions that are responsible for solving a piece of a business problem rather than functions that help implement that solution.</p><p>In case I need to refactor how that piece of code is implemented, I can change the internals of the code however I want, as long as the tests still pass. Refactoring or even removing a low-level function doesn’t affect tests, because they’re not tested directly.</p><p>Be minded, I’m not encouraging you to stop testing low-level functions.</p><p>I’m encouraging you to focus on tests that give you the most confidence in the code. The confidence that it solves a specific problem. Not the confidence that it’s implemented in a specific way.</p><p>Focus on testing things that you’ll interact with often or public interfaces that someone else will use.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e8b557b89198" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How TDD Helps You Prototype Faster By Allowing You To Experiment With Your Code]]></title>
            <link>https://jakubsobolewski.medium.com/how-tdd-helps-you-prototype-faster-by-allowing-you-to-experiment-with-your-code-e6c755d1a46d?source=rss-7222fc8ef8b8------2</link>
            <guid isPermaLink="false">https://medium.com/p/e6c755d1a46d</guid>
            <category><![CDATA[unit-testing]]></category>
            <category><![CDATA[rstats]]></category>
            <category><![CDATA[testing]]></category>
            <category><![CDATA[test-driven-development]]></category>
            <category><![CDATA[r]]></category>
            <dc:creator><![CDATA[Jakub Sobolewski]]></dc:creator>
            <pubDate>Sun, 20 Oct 2024 11:42:21 GMT</pubDate>
            <atom:updated>2024-10-20T11:42:21.727Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*mjjufYMDxieMYmtZDOvaQg.png" /></figure><p>Writing tests may be seen as a thing that slows you down because it makes you write more code.</p><p>Not if you start development by writing tests. Those tests help you find a better solution sooner. You save time on rewriting production code in case it turns out to be not flexible enough. Tests written first are also more robust because they prevent you from testing implementation details, which don’t exist yet! You save time on rewriting brittle tests.</p><p>Let’s imagine we need to write code that validates a data.frame against some rules.</p><pre>describe(&quot;validate&quot;, {<br>  it(&quot;should return TRUE if data passes validation&quot;, {<br><br>  })<br>})</pre><p>We need data and validation rules. We don’t need to know how to represent validation rules yet. It may be just a ValidationRules object. We can come back to it later.</p><pre>describe(&quot;validate&quot;, {<br>  it(&quot;should return TRUE if data passes validation&quot;, {<br>    # Arrange<br>    data &lt;- data.frame(x = 1, y = &quot;a&quot;)<br>    validation_rules &lt;- structure(<br>      list(),<br>      class = &quot;ValidationRules&quot;<br>    )<br>  })<br>})</pre><p>What matters is that we know we need a representation for those rules. We obtain a <strong>separation of concerns</strong>, rules are <strong>decoupled</strong> from this validator.</p><pre>describe(&quot;validate&quot;, {<br>  it(&quot;should return TRUE if data passes validation&quot;, {<br>    # Arrange<br>    data &lt;- data.frame(x = 1, y = &quot;a&quot;)<br>    validation_rules &lt;- structure(<br>      list(),<br>      class = &quot;ValidationRules&quot;<br>    )<br>  })<br>})</pre><p>We might want to represent the validator with R6 class object. Let’s initialize it with data and validation rules.</p><pre>describe(&quot;validate&quot;, {<br>  it(&quot;should return TRUE if data passes validation&quot;, {<br>    # Arrange<br>    data &lt;- data.frame(x = 1, y = &quot;a&quot;)<br>    validation_rules &lt;- structure(<br>      list(),<br>      class = &quot;ValidationRules&quot;<br>    )<br>    validator &lt;- data_validator$new(data, validation_rules)<br>  })<br>})</pre><p>It may have a validate method that returns a flag indicating if the data passes validation.</p><pre>describe(&quot;validate&quot;, {<br>  it(&quot;should return TRUE if data passes validation&quot;, {<br>    # Arrange<br>    data &lt;- data.frame(x = 1, y = &quot;a&quot;)<br>    validation_rules &lt;- structure(<br>      list(),<br>      class = &quot;ValidationRules&quot;<br>    )<br>    validator &lt;- data_validator$new(data, validation_rules)<br><br>    # Act<br>    result &lt;- validator$validate()<br><br>    # Assert<br>    expect_true(result)<br>  })<br>})</pre><p>We can already see that this may be not flexible enough. We construct the object with data and validation rules.</p><pre>describe(&quot;validate&quot;, {<br>  it(&quot;should return TRUE if data passes validation&quot;, {<br>    # Arrange<br>    data &lt;- data.frame(x = 1, y = &quot;a&quot;)<br>    validation_rules &lt;- structure(<br>      list(),<br>      class = &quot;ValidationRules&quot;<br>    )<br>    validator &lt;- data_validator$new(data, validation_rules)<br><br>    # Act<br>    result &lt;- validator$validate()<br><br>    # Assert<br>    expect_true(result)<br>  })<br>})</pre><p>Let’s go back to validation rules. We might experiment with them being a list of checkmate assertions.</p><pre>describe(&quot;validate&quot;, {<br>  it(&quot;should return TRUE if data passes validation&quot;, {<br>    # Arrange<br>    data &lt;- data.frame(x = 1, y = &quot;a&quot;)<br>    validation_rules &lt;- structure(<br>      list(<br>        \(x) checkmate::test_data_frame(x),<br>        \(x) checkmate::test_subset(c(&quot;x&quot;, &quot;y&quot;), colnames(x))<br>      ),<br>      class = &quot;ValidationRules&quot;<br>    )<br>    validator &lt;- data_validator$new(validation_rules)<br><br>    # Act<br>    result &lt;- validator$validate(data)<br><br>    # Assert<br>    expect_true(result)<br>  })<br>})</pre><p>Or an object that provides a {pointblank} agent.</p><pre>describe(&quot;validate&quot;, {<br>  it(&quot;should return TRUE if data passes validation&quot;, {<br>    # Arrange<br>    data &lt;- data.frame(x = 1, y = &quot;a&quot;)<br>    validation_rules &lt;- structure(<br>      list(get = function() {<br>        pointblank::create_agent(tbl = ~ x) |&gt;<br>          pointblank::col_exists(columns = c(&quot;x&quot;, &quot;y&quot;))<br>      }),<br>      class = &quot;ValidationRules&quot;<br>    )<br>    validator &lt;- data_validator$new(validation_rules)<br><br>    # Act<br>    result &lt;- validator$validate(data)<br><br>    # Assert<br>    expect_true(result)<br>  })<br>})</pre><p>If we take the time to write tests first we can quickly iterate different ideas and arrive at a better solution faster.</p><ul><li>We’ll probably end up with code that is easy to use.</li><li>One that has better separation of concerns.</li><li>One that promotes dependency injection.</li></ul><p>Start development from tests and save time on rewrites and refactors. Writing tests first pays off very quickly.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e6c755d1a46d" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Testing Code With External Dependencies]]></title>
            <link>https://jakubsobolewski.medium.com/testing-code-with-external-dependencies-900073cb688f?source=rss-7222fc8ef8b8------2</link>
            <guid isPermaLink="false">https://medium.com/p/900073cb688f</guid>
            <category><![CDATA[unit-testing]]></category>
            <category><![CDATA[rstats]]></category>
            <category><![CDATA[r]]></category>
            <category><![CDATA[testing]]></category>
            <category><![CDATA[data-science]]></category>
            <dc:creator><![CDATA[Jakub Sobolewski]]></dc:creator>
            <pubDate>Fri, 18 Oct 2024 19:42:01 GMT</pubDate>
            <atom:updated>2024-10-18T19:42:01.729Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/848/1*h5JT82rT6ypTkvbvqHM6cg.png" /></figure><p>A stub is a controllable replacement of a dependency in your system.</p><p>Stubbing helps you test your code without directly interacting with a dependency, e.g., an API.</p><p>How to test the_ultimate_question_of function if the_answer:</p><ul><li>Requires a connection to an external service?</li><li>Or it takes millions of years to compute?</li></ul><pre>#&#39; R/the_ultimate_question_of.R<br>the_ultimate_question_of &lt;- function(<br>  x = c(&quot;Life&quot;, &quot;Universe&quot;, &quot;Everything&quot;)<br>) {<br>  x &lt;- match.arg(x)<br>  the_answer(x)<br>}</pre><p>Let’s write our first test.</p><pre>#&#39; tests/testthat/test-the_ultimate_question_of.R<br>test_that(&quot;the_ultimate_question_of returns 42&quot;, {<br>  # Arrange<br>  input &lt;- &quot;Everything&quot;<br><br>  # Act<br>  result &lt;- the_ultimate_question_of(input)<br><br>  # Assert<br>  expect_equal(result, ???)<br>})</pre><p>We need to stub the the_answer.</p><p>We can use testthat::local_mocked_bindings.</p><pre>#&#39; tests/testthat/test-the_ultimate_question_of.R<br>test_that(&quot;the_ultimate_question_of returns 42&quot;, {<br>  # Arrange<br>  local_mocked_bindings(the_answer = function(x) 42)<br>  input &lt;- &quot;Everything&quot;<br><br>  # Act<br>  result &lt;- the_ultimate_question_of(input)<br><br>  # Assert<br>  expect_equal(result, ???)<br>})</pre><p>Then we can assert that the answer to &quot;Everything&quot; is 42.</p><pre>#&#39; tests/testthat/test-the_ultimate_question_of.R<br>test_that(&quot;the_ultimate_question_of returns 42&quot;, {<br>  # Arrange<br>  local_mocked_bindings(<br>    the_answer = function(x) 42<br>  )<br><br>  input &lt;- &quot;Everything&quot;<br><br>  # Act<br>  result &lt;- the_ultimate_question_of(input)<br><br>  # Assert<br>  expect_equal(result, 42)<br>})</pre><p>Before {testthat} version 3.2.0, mockery::stub had to be used.</p><pre>#&#39; tests/testthat/test-my_function.R<br>test_that(&quot;the_ultimate_question_of returns 42&quot;, {<br>  # Arrange<br>  mockery::stub(<br>    where = the_ultimate_question_of,<br>    what = &quot;the_answer&quot;,<br>    how = 42<br>  )<br>  input &lt;- &quot;Everything&quot;<br><br>  # Act<br>  result &lt;- the_ultimate_question_of(input)<br><br>  # Assert<br>  expect_equal(result, 42)<br>})</pre><p>So testthat::local_mocked_bindings:</p><ul><li>Allows you to stub functions without adding new dependencies.</li><li>It works with packages only — {mockery} doesn’t have this constraint.</li><li>Stubbed function must be declared in the environment.</li></ul><p>testthat::local_mocked_bindings let’s you quickly start with stubbing in your tests.</p><p>For more advanced use cases you still need to rely on {mockery}.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=900073cb688f" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Don’t Expect That “Function Works Correctly”, Do This Instead]]></title>
            <link>https://jakubsobolewski.medium.com/dont-expect-that-function-works-correctly-do-this-instead-5fbc71d1fc6d?source=rss-7222fc8ef8b8------2</link>
            <guid isPermaLink="false">https://medium.com/p/5fbc71d1fc6d</guid>
            <category><![CDATA[r]]></category>
            <category><![CDATA[unit-testing]]></category>
            <dc:creator><![CDATA[Jakub Sobolewski]]></dc:creator>
            <pubDate>Mon, 14 Oct 2024 19:20:58 GMT</pubDate>
            <atom:updated>2024-10-18T19:43:49.597Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/878/1*wPi5aF1E9_Bq1dxjvyTvew.png" /></figure><p>When writing code, we pay a lot of attention to naming variables. We want to make sure that the name of the variable is descriptive and helps us understand what the variable is used for. We should apply the same principle to our tests.</p><p>When writing unit tests, especially when writing unit tests after the production code, it’s tempting to write a bunch of assertions and give them a title like “[function] works correctly”. Since we’ve already implemented it and manually checked that it works correctly, what else is there to write?</p><p>The problem with this approach is that it doesn’t help us understand what the tested code is doing. If we come back to code even a few days later, we might not remember how the function is supposed to work.</p><p>Let’s consider a simple example. We have a function `median` that calculates the median of a vector. We can write a test like this:</p><pre>test_that(&quot;median works correctly&quot;, {<br>  expect_equal(median(c(1)), 1)<br>  expect_equal(median(c(1, 2)), 1.5)<br>  expect_equal(median(c(2, 1)), 1.5)<br>  expect_equal(median(c(1, 2, 3)), 2)<br>  expect_equal(median(c(3, 2, 1)), 2)<br>  expect_equal(median(c(5, 2, 4, 3, 1)), 3)<br>})</pre><p>Looking at this test, we might infer that the function handles a few cases:</p><ul><li>it should return the same value if the vector has only one element,</li><li>it should return the average of two values if the vector has an even number of elements,</li><li>it should return the middle value if the vector has an odd number of elements,</li><li>it should work for both ordered and unordered vectors.</li></ul><p>Instead of having to infer this information from the test, we can write the test in a way that makes it clear what the function is supposed to do. We can write a separate test for each of the cases:</p><pre>test_that(&quot;median should return the same value if the vector has only one element&quot;, {<br>  expect_equal(median(c(1)), 1)<br>})<br><br>test_that(&quot;median should return the average of two values if the vector has even number of elements&quot;, {<br>  expect_equal(median(c(2, 1)), 1.5)<br>})<br><br>test_that(&quot;median should return the middle value if the vector has an odd number of elements&quot;, {<br>  expect_equal(median(c(5, 2, 4, 3, 1)), 3)<br>})<br><br>test_that(&quot;median should return the same value for ordered and unordered vectors&quot;, {<br>  expect_equal(median(c(4, 3, 2, 1)), median(c(1, 2, 3, 4)))<br>  expect_equal(median(c(5, 2, 4, 3, 1)), median(c(1, 2, 3, 4, 5)))<br>})</pre><p>There is a reason why <em>testthat::test_that</em> function is called “test that”. It’s to allow us to read the test as a sentence, making it easier to understand what the function is supposed to do.</p><p>Using <em>test_that</em> is perfectly fine, but we can make this test organized in a slightly different way by utilizing <em>testthat::describe</em> and <em>testthat::it</em>.</p><pre>describe(&quot;median&quot;, {<br>  it(&quot;should return the same value if the vector has only one element&quot;, {<br>    expect_equal(median(c(1)), 1)<br>  })<br><br>  it(&quot;should return the average of two values if the vector has even number of elements&quot;, {<br>    expect_equal(median(c(2, 1)), 1.5)<br>  })<br><br>  it(&quot;should return the middle value if the vector has an odd number of elements&quot;, {<br>    expect_equal(median(c(5, 2, 4, 3, 1)), 3)<br>  })<br><br>  it(&quot;should return the same value for ordered and unordered vectors&quot;, {<br>    expect_equal(median(c(4, 3, 2, 1)), median(c(1, 2, 3, 4)))<br>    expect_equal(median(c(5, 2, 4, 3, 1)), median(c(1, 2, 3, 4, 5)))<br>  })<br>})</pre><p>This approach is even more focused on describing how the code behaves.</p><p>In this simple example, it might take us a few seconds to understand what the function is supposed to do, and coming up with a good description might be more costly than having to read and understand the test.</p><p>This might be true, but this time will be multiplied each time a person comes back to this code.</p><p>When we are testing more complex code, the advantages are more pronounced.</p><p>When writing test titles, think about your future self and your colleagues. Make sure that the tests are easy to read and understand. Make sure that test titles describe what the function is supposed to do, not just that it works correctly.</p><p>If you want to push test readability even further, check out how we can use <a href="https://jakubsob.github.io/blog/want-cleaner-test-try-arrange-act-assert/">Arrange-Act-Assert</a> pattern to achieve that.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5fbc71d1fc6d" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Testing components with shinytest2]]></title>
            <link>https://blog.devgenius.io/testing-components-with-shinytest2-948119461ccc?source=rss-7222fc8ef8b8------2</link>
            <guid isPermaLink="false">https://medium.com/p/948119461ccc</guid>
            <category><![CDATA[r]]></category>
            <category><![CDATA[testing]]></category>
            <category><![CDATA[shiny]]></category>
            <dc:creator><![CDATA[Jakub Sobolewski]]></dc:creator>
            <pubDate>Thu, 23 May 2024 00:00:39 GMT</pubDate>
            <atom:updated>2024-10-29T15:03:50.715Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*H74nC4SYJQeyl194eJ1C2g.png" /></figure><p>Components in Shiny not only need to be rendered with correct markup, but also need to successfully communicate with the server. This means that testing the markup only may be not enough to ensure they function correctly.</p><p>In the newest addition to <a href="https://appsilon.github.io/shiny.blueprint/">shiny.blueprint</a>, server update functions are added to some of its components. To test that they work correctly, we must:</p><ul><li>render the component with initial values,</li><li>trigger the update,</li><li>check the new value.</li></ul><h3>How to run a component with Shiny server?</h3><p><strong>One approach is to bunch up a few (or all) components in one Shiny app.</strong> This could allow sharing one app between tests, saving on the time it takes to start up the app, but it would require additional coordination between tests.</p><p>Such choice was made for component tests in <a href="https://appsilon.github.io/shiny.fluent/">shiny.fluent</a>, the <a href="https://github.com/Appsilon/shiny.fluent/tree/main/inst/examples/e2e-test">test app</a> is placed in inst/ directory and a series of <a href="https://github.com/Appsilon/shiny.fluent/tree/main/js/cypress/e2e/e2e-test">Cypress tests</a> are run on it. This approach works well, because Cypress quickly refreshes the app between each test case, ensuring clean state in each test case. shinytest2 doesn&#39;t have this feature.</p><p>This approach is a bit tricky to maintain, as there are a lot of things rendered on the page.</p><p><strong>The other approach is to run a small Shiny app with only the tested component.</strong></p><h3>Running components in isolation</h3><p>We can create an app factory that accepts components and their corresponding update functions as parameters.</p><pre>#&#39; tests/testtthat/setup.R<br>#&#39; @param component Function, returns the component to test<br>#&#39; @param update Function, updates the component<br>serverUpdateApp &lt;- function(<br>  component = \() { },<br>  update = \(session) { }<br>) {<br>  shinytest2::AppDriver$new(<br>    shiny::shinyApp(<br>      ui = shiny::fluidPage(<br>        shiny::actionButton(&quot;trigger&quot;, &quot;Trigger&quot;),<br>        component()<br>      ),<br>      server = function(input, output, session) {<br>        shiny::observeEvent(input$trigger, update(session))<br>      }<br>    )<br>  )<br>}<br><br>#&#39; @param inputId The ID of the tested component<br>#&#39; @param driver shinytest2::AppDriver of the test app<br>serverUpdateActions &lt;- function(inputId, driver) {<br>  list(<br>    update = function() {<br>      driver$click(&quot;trigger&quot;)<br>    },<br>    getValue = function() {<br>      driver$get_value(input = inputId)<br>    }<br>  )<br>}</pre><p>This simple app showcases the behavior we want to test. It will render the component and allow triggering the update. It’s simple, and it’s enough to test this behavior.</p><p>We can create a different app, with different parametrization, for testing other behaviors.</p><h3>If testing consists of the same steps, there is an opportunity to abstract test code.</h3><p>We can provide a list of actions tests can take on this app — they hide implementation details of those interactions. Tests don’t need to know that a button is clicked to trigger the update, they only know that the update happens. They also don’t need to know how the value is retrieved, only that it is and expect a value. This way, we can change the implementation of those actions without changing the tests in the future.</p><p>This is how a test for a Checkbox component looks like:</p><pre>#&#39; tests/testthat/test-Checkbox.R<br>describe(&quot;Checkbox&quot;, {<br>  it(&quot;should allow updating values from the server&quot;, {<br>    # Arrange<br>    driver &lt;- serverUpdateApp(<br>      \() Checkbox.shinyInput(&quot;checkbox&quot;, value = FALSE),<br>      \(session) {<br>        updateCheckbox.shinyInput(<br>          session,<br>          inputId = &quot;checkbox&quot;,<br>          value = TRUE<br>        )<br>      }<br>    )<br>    on.exit(driver$stop())<br>    actions &lt;- serverUpdateActions(&quot;checkbox&quot;, driver)<br><br>    # Act<br>    actions$update()<br><br>    # Assert<br>    expect_true(actions$getValue())<br>  })<br>})</pre><p>and for NumericInput:</p><pre>describe(&quot;NumericInput&quot;, {<br>  it(&quot;should allow updating values from the server&quot;, {<br>    # Arrange<br>    driver &lt;- serverUpdateApp(<br>      \() {<br>        NumericInput.shinyInput(<br>          inputId = &quot;numeric&quot;,<br>          value = 1,<br>          label = &quot;Numeric&quot;<br>        )<br>      },<br>      \(session) {<br>        updateNumericInput.shinyInput(<br>          session,<br>          inputId = &quot;numeric&quot;,<br>          value = 2<br>        )<br>      }<br>    )<br>    on.exit(driver$stop())<br>    actions &lt;- serverUpdateActions(&quot;numeric&quot;, driver)<br><br>    # Act<br>    actions$update()<br><br>    # Assert<br>    expect_equal(actions$getValue(), 2)<br>  })<br>})</pre><p>Test code for both cases is similar, and it’s good, as they test the same behavior.</p><h3>This approach provides:</h3><ul><li>✅ <strong>Clarity</strong>: it’s easy to see which behaviors are tested for each component.</li><li>✅ <strong>Flexibility</strong>: we can control how each component is tested in its own test file.</li><li>✅ <strong>Reduced cognitive load</strong>: tests that test the same behavior are implemented using the same approach.</li><li>❌ <strong>Slower tests</strong>: it takes a moment to spin up each test app. The time it takes to run all tests increases with each added test case.</li><li>✅ <strong>No state sharing between tests</strong>: each test runs in isolation, so there are no side effects.</li><li>⚠️ <strong>More test code</strong>: test code is split into more files and has more boilerplate. There is a fine line between too much test code and too much abstraction. I think in this case it’s a good trade-off.</li></ul><p>Check out the full scope of the changes <a href="https://github.com/Appsilon/shiny.blueprint/pull/104/files#diff-6a4f3c75c8d32b37ec5f88889d89b5ec996616e0f30c7219baacc8f3bf4ad41b">here</a>.</p><p><em>Originally published at </em><a href="https://jakubsob.github.io/blog/testing-components-with-shinytest2/"><em>https://jakubsob.github.io</em></a><em> on May 23, 2024.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=948119461ccc" width="1" height="1" alt=""><hr><p><a href="https://blog.devgenius.io/testing-components-with-shinytest2-948119461ccc">Testing components with shinytest2</a> was originally published in <a href="https://blog.devgenius.io/">Dev Genius</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[3-Step Guide For Building Plots Faster With Test Driven Development]]></title>
            <link>https://jakubsobolewski.medium.com/3-step-guide-for-building-plots-faster-with-test-driven-development-b7675e7aa4f8?source=rss-7222fc8ef8b8------2</link>
            <guid isPermaLink="false">https://medium.com/p/b7675e7aa4f8</guid>
            <category><![CDATA[r]]></category>
            <category><![CDATA[data-visualization]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[testing]]></category>
            <category><![CDATA[software-development]]></category>
            <dc:creator><![CDATA[Jakub Sobolewski]]></dc:creator>
            <pubDate>Sun, 29 Oct 2023 13:31:50 GMT</pubDate>
            <atom:updated>2024-10-20T11:49:09.467Z</atom:updated>
            <content:encoded><![CDATA[<h3>3-Step Guide For Building Plots Faster With Test Driven Development.</h3><p>Unit-testing plots is challenging, as images are difficult to describe in code.</p><p>We need to rely on <a href="https://understandlegacycode.com/approval-tests/">approval testing</a>, which is usually utilized to validate that an output remains the same when code changes. But we don’t have a plot yet that we can assert on, how can we use Test Driven Development (TDD) and start from writing tests? Where to even start?</p><p>Let’s see how we can get the most benefits of TDD and approval testing to rapidly develop a plot.</p><h3>1. Start with a test</h3><p>We start in (almost) the same way as we would do with any other piece of software using TDD:</p><ul><li>Write test first.</li><li>Run it to see if it fails 🔴.</li><li>Write production code to pass the test 🟢.</li><li>Refactor ♻️.</li></ul><p>Make sure to do those steps in order, as only as you unlock the full potential of this approach!</p><p><strong>When writing tests, focus on:</strong></p><ul><li>Describing what the plot <strong>should</strong> look like — make different outcomes separate test cases. Be verbose, use as many words as you need to describe <strong>how</strong> the plot <strong>should behave.</strong></li><li>Creating <strong>a minimal setup</strong> to satisfy the requirements — remember about <strong>chicken counting: zero, one, many.</strong> If you want to test rendering of multiple series, two will probably suffice. Add a separate case to test limits of how much data can be plotted.</li></ul><p>Let’s create a simple scatter plot with a regression line.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2qtPepG7c0JWx3tpjbajEQ.png" /></figure><p>Notice we use fail() in each test.</p><p>We don’t have an automated way of checking results yet, so we should expect tests to always fail 🔴 — our code is not in a releasable state yet! When we have tests in place, we can start adding production code.</p><p>Don’t write more code than it’s enough to satisfy tests — YAGNI!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*t7h7_-Yc4AQXLCAj2I326A.png" /></figure><h3>2. Preview results for iterating quickly</h3><p>We could add snapshots assertions at this stage, but since we’re still developing the plot:</p><ul><li>Adding new test cases for new features.</li><li>Adding new test cases for edge cases.</li><li>Or experimenting with a theme.</li></ul><p>It would add an overhead of reviewing and accepting new snapshots.</p><p>To make development more rapid, we can just add print calls before each fail() to manually inspect plots with each change, it will speed up each iteration, but:</p><ul><li>With more cases, it’ll become more difficult to manually inspect them all.</li><li>You can start breaking other features without noticing — computers are way better on comparing if things are identical than humans!</li></ul><p>So don’t linger in this stage for too long!</p><h3>3. Add assertions on plot snapshots</h3><p>Once we get to a stage when most features are stable, and we can finally add actual snapshot tests.</p><p>We can use <a href="https://github.com/r-lib/vdiffr">vdiffr</a> package and its expect_doppelganger method:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/908/1*YB_Pa-yKT6tGnDNT23hifA.png" /></figure><p>Or we could use testthat::expect_snapshot_file, but then we’d need to handle saving the plot to a file on our own.</p><p><strong>Notice that we don’t assert on the plot object, its representation in the R process, but we’re asserting on the object printed to the screen.</strong></p><p>Assertion set up in such a way will do the following:</p><ul><li>On the first run, it will save a snapshot for each test case.</li><li>On subsequent runs, it will check if the new figure is the same as the one saved.</li><li>If the figure is the same, the test passes! 🟢</li><li>If the figure is different, the test will fail 🔴 — you will be prompted to check the difference (e.g., using testthat::snapshot_review()) and either:</li><li>Reject the change — the change is not an expected one, we still want to use previous snapshot as the correct one.</li><li>Approve the change — new snapshot will override previous one and will be used for subsequent test runs. That’s why it’s called an <strong>Approval Test.</strong></li></ul><p>Make sure to encode your system information into the snapshot (e.g., with shinytest2::platform_variant()) — if you use a different system in CI, snapshots generated locally can be different from ones in the CI and the pipeline will fail.</p><p>If we follow this approach, we obtain:</p><ul><li>A <strong>proof</strong> that we produced images that we accept as ones meeting <strong>all requirements.</strong></li><li>A textual documentation of how the plot <strong>should look like.</strong></li><li>A number of <strong>examples how the plot code can be called.</strong></li><li>And a side effect of <strong>100% test coverage.</strong></li></ul><p>Start using Test Driven Development today and enjoy instant feedback on what your code does and improved safety that your code keeps working as expected!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b7675e7aa4f8" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[3 Types Of Unit Tests That Everyone Should Know]]></title>
            <link>https://jakubsobolewski.medium.com/3-types-of-unit-tests-that-everyone-should-know-8197bc5b712d?source=rss-7222fc8ef8b8------2</link>
            <guid isPermaLink="false">https://medium.com/p/8197bc5b712d</guid>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[r]]></category>
            <category><![CDATA[unit-testing]]></category>
            <category><![CDATA[testing]]></category>
            <category><![CDATA[data-science]]></category>
            <dc:creator><![CDATA[Jakub Sobolewski]]></dc:creator>
            <pubDate>Wed, 18 Oct 2023 18:09:39 GMT</pubDate>
            <atom:updated>2024-10-20T11:48:33.211Z</atom:updated>
            <content:encoded><![CDATA[<p>When approaching to write a unit test, we might ask ourselves:</p><ul><li><strong>What</strong> should I test?</li><li><strong>How</strong> should I test?</li><li>And even <strong>when</strong> should I test?</li></ul><p>Getting answers to these questions helps overcome writer’s block.</p><p>To make it easier to think about <strong>what</strong> to test and to make a more informed decision on <strong>how</strong> we need to test it, we may categorize tests into:</p><ul><li>Direct Response Tests.</li><li>State Change Tests.</li><li>Interaction Tests.</li></ul><p>Let’s see in what circumstances should each type be used.</p><h3>Direct Response Tests</h3><ul><li>They check whether a return value or an exception matches the expectation.</li><li>These tests ensure that the core functionality of the code works correctly.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*p73fRoXd_YVOfJjBfEcI3Q.png" /><figcaption>Direct response test.</figcaption></figure><h3>Tips</h3><ul><li>Don’t test a lot of different values if the new combination doesn’t test new behavior. E.g., testing mean(1:10) and then mean(1:100) doesn’t improve our confidence that mean function works as expected.</li><li>Use assertions to convey intent. E.g., if you don’t care about the order of a vector, consider using testthat::expect_setequal instead of testthat::expect_equal to only assert on its content.</li><li>Don’t duplicate assertions. E.g., if you already use testthat::expect_equal on a vector, does adding an assertion on its length with testthat::expect_length add more safety?</li></ul><h3>State Change Tests</h3><ul><li>These tests help validate the impact of certain actions on the system’s state.</li><li>They confirm that the behavior results in the expected changes, such as modifying a list and confirming its size change.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/996/1*EmIdk9O3o3Cc2NlngWfbfw.png" /><figcaption>State change test.</figcaption></figure><h3>Tips</h3><ul><li>Don’t share state between tests. It may make tests more fragile and more difficult to understand.</li><li>Avoid iteration. Don’t check if Stack can handle 0, 1, 2, 3, 4, …, calls to push. Use chicken counting: <strong>zero, one, or many.</strong></li></ul><h3>Interaction Tests</h3><ul><li>These tests ensure proper communication and integration between different parts of the system.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/922/1*pJnLj7NWhxJy7OTO_3ZHig.png" /><figcaption>Interaction test.</figcaption></figure><ul><li>These tests examine how code interacts with external components, often simulating dependencies or external services. <a href="http://xunitpatterns.com/Mocks,%20Fakes,%20Stubs%20and%20Dummies.html"><strong>Mocks, Fakes, Stubs and Dummies</strong></a> are used to control these interactions and validate that the code interacts correctly with external entities.</li></ul><h3>Tips</h3><ul><li>Complex mock will make tests brittle and difficult to understand. They typically need to be created when interactions in the code are complex or not defined well enough.</li><li>Notice how much setup is needed to run a test. Use this feedback to improve and simplify production code. Code that is easy to test is easier to maintain.</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8197bc5b712d" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>