<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0" xmlns:atom="http://www.w3.org/2005/Atom" xmlns:dc="http://purl.org/dc/elements/1.1/">
  <channel>
    <title>DEV Community: Amir Maralani</title>
    <description>The latest articles on DEV Community by Amir Maralani (@amaralani).</description>
    <link>https://dev.to/amaralani</link>
    <image>
      <url>https://media2.dev.to/dynamic/image/width=90,height=90,fit=cover,gravity=auto,format=auto/https:%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Fuser%2Fprofile_image%2F472837%2F9f076ad5-5237-4b17-aeea-09b2791fa3f6.jpeg</url>
      <title>DEV Community: Amir Maralani</title>
      <link>https://dev.to/amaralani</link>
    </image>
    <atom:link rel="self" type="application/rss+xml" href="https://dev.to/feed/amaralani"/>
    <language>en</language>
    <item>
      <title>My first Serverless service</title>
      <dc:creator>Amir Maralani</dc:creator>
      <pubDate>Mon, 21 Dec 2020 06:33:17 +0000</pubDate>
      <link>https://dev.to/amaralani/my-first-serverless-service-3233</link>
      <guid>https://dev.to/amaralani/my-first-serverless-service-3233</guid>
      <description>&lt;p&gt;Recently I was going to run a service on &lt;a href="https://www.fandogh.cloud/"&gt;Fandogh Paas&lt;/a&gt; with a custom domain and ended up using &lt;a href="https://www.cloudflare.com/"&gt;Cloudflare&lt;/a&gt;. When setting up stuff something caught my eye: &lt;strong&gt;&lt;em&gt;Workers&lt;/em&gt;&lt;/strong&gt;. I knew about the concept of &lt;em&gt;Serverless&lt;/em&gt; a little but due to the circumstances using &lt;em&gt;AWS&lt;/em&gt; is somewhat out of reach for me, so why not use this instead?!&lt;/p&gt;

&lt;p&gt;I tried to create something with it. But the big question was what to build. Last year I created a little &lt;em&gt;Discord&lt;/em&gt; bot to retrieve the current AQI of the provided city but since we are not using Discord anymore it's obsolete. Let's do it serverless this time!&lt;/p&gt;

&lt;p&gt;The idea of using serverless to just call another API and pass the response on looks a bit redundant, but I guess it's good enough for learning new stuff. So I got an API token from &lt;a href="https://aqicn.org/api/"&gt;Air Quality Open Data Platform&lt;/a&gt; and started coding.&lt;/p&gt;

&lt;p&gt;There's a fair amount of documents and examples on the &lt;a href="https://workers.cloudflare.com"&gt;Cloudflare Workers&lt;/a&gt; site, and of course, you will need enough JavaScript knowledge.&lt;/p&gt;

&lt;p&gt;Here's my code :&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const aqiInfoUrl = "https://api.waqi.info/feed/"

addEventListener('fetch', event =&amp;gt; {
  event.respondWith(handleRequest(event.request))
})

/**
 * Respond to the request
 * @param {Request} request
 */
async function handleRequest(request) {
  const queryString = request.url.split('?');
  let city = queryString[1].split('=')[1];

  let response = await getAQIFromAPI(city);
  return new Response(response.data.aqi, {status: 200});
}

async function getAQIFromAPI(city) {
  let fullUrl = aqiInfoUrl + city + '/?token='+ API_TOKEN;
  const response = await fetch(fullUrl);
  return await response.json();
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;What it basically does is that when called, tries to find the city from the query string and sends a request to "&lt;a href="https://api.waqi.info/feed/"&gt;https://api.waqi.info/feed/&lt;/a&gt;" with the provided city and the token which is saved as an environment variable.&lt;/p&gt;

&lt;p&gt;It is not the best way it could be written, but I'm very new to this! Please give me your suggestions in the comment section. &lt;/p&gt;

&lt;p&gt;PS: I'm thinking about a Telegram bot using the KV store ... Maybe the next post!&lt;/p&gt;

</description>
      <category>serverless</category>
      <category>cloudflare</category>
      <category>workers</category>
    </item>
    <item>
      <title>How not to design an Enum (Java)</title>
      <dc:creator>Amir Maralani</dc:creator>
      <pubDate>Sun, 29 Nov 2020 06:59:49 +0000</pubDate>
      <link>https://dev.to/amaralani/how-not-to-design-an-enum-java-3mkn</link>
      <guid>https://dev.to/amaralani/how-not-to-design-an-enum-java-3mkn</guid>
      <description>&lt;p&gt;Throughout the years, I've seen and created many Enums in Java. Some of them were very useful, some just avoided a bit of hard-code and a few bad ones.&lt;/p&gt;

&lt;p&gt;This is an example of a very bad enum design. I'm not blaming anyone else, I was a contributor to this. But in my defense I was a newbie then. Let's take a look at it :&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;public enum EventStatusType {
    /**
     * event is processed {0 value in database}
     */
    PROCESSED,
    /**
     *  event is not processed {1 value in database}
     */
    UNPROCESSED,
    /**
     * event is now running {2 value in database}
     */
    IN_PROGRESS,
    /**
     * event has failed {3 value in database}
     */
    FAILED
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;First of all, what's with the name? It's either a &lt;em&gt;Status&lt;/em&gt; or a &lt;em&gt;Type&lt;/em&gt;, which in this case it's a status, so &lt;code&gt;EventStatus&lt;/code&gt; would be a better name. &lt;/p&gt;

&lt;p&gt;Then we get to the JavaDocs. They are not explaining anything. Instead of explaining for example what does it mean that the event is &lt;code&gt;in progress&lt;/code&gt; they are just a repetition of the values. Also, the mention of what they represent in the database is absolutely useless, redundant, and even incorrect. Useless and redundant because everyone working with enums and saving them by their ordinals in a database should know how they work. Incorrect because if we change the type used in our entity to &lt;code&gt;String&lt;/code&gt;, we should not be forced to change the JavaDoc for the enum.&lt;/p&gt;

&lt;p&gt;The other utterly annoying thing in this enum is its order. When watching the database to check the status of the events, you encounter some records with statuses of &lt;code&gt;0&lt;/code&gt;, &lt;code&gt;1&lt;/code&gt;, &lt;code&gt;2&lt;/code&gt;, and &lt;code&gt;3&lt;/code&gt;. Your intuition says the &lt;code&gt;0&lt;/code&gt; is the base value, then the event status would move on to &lt;code&gt;1&lt;/code&gt; and &lt;code&gt;2&lt;/code&gt; (or &lt;code&gt;3&lt;/code&gt;). And you are wrong. The base value is &lt;code&gt;1&lt;/code&gt;, then you move to &lt;code&gt;2&lt;/code&gt; and the final status is either &lt;code&gt;0&lt;/code&gt; or &lt;code&gt;3&lt;/code&gt;. Very counter-intuitive.&lt;/p&gt;

&lt;p&gt;Taking care of the mentioned issues with this code would improve the readability and ease of maintenance.&lt;/p&gt;

&lt;p&gt;Do you have any more suggestions? Please share it with me.&lt;/p&gt;

</description>
      <category>java</category>
    </item>
    <item>
      <title>Logging all request mappings and their parameters in Spring</title>
      <dc:creator>Amir Maralani</dc:creator>
      <pubDate>Sat, 21 Nov 2020 10:30:46 +0000</pubDate>
      <link>https://dev.to/amaralani/logging-all-request-mappings-and-their-parameters-in-spring-30fa</link>
      <guid>https://dev.to/amaralani/logging-all-request-mappings-and-their-parameters-in-spring-30fa</guid>
      <description>&lt;p&gt;Today we had a bit of a challenge ahead of our team. The guys in charge of the network and security of our client asked us to provide a list of all URLs that your application accepts, including the parameters.&lt;br&gt;
Since there are tens of controllers in our application that have tens of methods inside them it was not a manual task to do anymore. After a bit of looking around, I decided to implement it using &lt;code&gt;ApplicationListener&lt;/code&gt;. Any class implementing &lt;code&gt;ApplicationListener&lt;/code&gt; will listen to the corresponding event and when the event occurs, fires the &lt;code&gt;onApplicationEvent&lt;/code&gt; method.&lt;/p&gt;

&lt;p&gt;For us, the event was &lt;code&gt;ContextRefreshedEvent&lt;/code&gt;. I wanted to have a list of all request mappings when the application starts up and also I wanted that list updated in case of a context refresh.&lt;/p&gt;

&lt;p&gt;So I receive the &lt;code&gt;ContextRefreshedEvent&lt;/code&gt;, extract the &lt;code&gt;ApplicationContext&lt;/code&gt;, get all handler methods and the request mappings, and finally extract the patterns and method parameters. This is my base implementation :&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;@Log4j
@Component
public class EndpointsListener implements ApplicationListener&amp;lt;ContextRefreshedEvent&amp;gt; {

    @SneakyThrows
    @Override
    public void onApplicationEvent(ContextRefreshedEvent event) {
        ApplicationContext applicationContext = event.getApplicationContext();
        List&amp;lt;Mapping&amp;gt; mappings = new ArrayList&amp;lt;&amp;gt;();
        for (Map.Entry&amp;lt;RequestMappingInfo, HandlerMethod&amp;gt; entry : applicationContext
                .getBean(RequestMappingHandlerMapping.class).getHandlerMethods().entrySet()) {
            RequestMappingInfo requestMappingInfo = entry.getKey();
            HandlerMethod handlerMethod = entry.getValue();
            Mapping mapping = new Mapping();
            mapping.setMethods(requestMappingInfo.getMethodsCondition().getMethods()
                    .stream().map(Enum::name).collect(Collectors.toSet()));
            mapping.setPatterns(requestMappingInfo.getPatternsCondition().getPatterns());
            Arrays.stream(handlerMethod.getMethodParameters()).forEach(methodParameter -&amp;gt; {


                    mapping.getParams().add(methodParameter.getParameter().getType().getSimpleName());

            });
            mappings.add(mapping);
        }

        mappings.sort(Comparator.comparing(o -&amp;gt; o.getPatterns().stream().findFirst().orElse("")));
        log.info(new ObjectMapper().writeValueAsString(mappings));
    }

    @Data
    public class Mapping {
        private Set&amp;lt;String&amp;gt; patterns;
        private Set&amp;lt;String&amp;gt; methods;
        private List&amp;lt;String&amp;gt; params;

        public List&amp;lt;String&amp;gt; getParams(){
            if(params == null) {
                params = new ArrayList&amp;lt;&amp;gt;();
            }
            return params;

        }
    }

}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;But there's a problem: we have quite a lot of view controllers defined in our implementation of &lt;code&gt;WebMvcConfigurer&lt;/code&gt;. Let's take a look :&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;@Override
public void addViewControllers(ViewControllerRegistry registry) {
   registry.addViewController("/new").setViewName("home");
   registry.addViewController("/home").setViewName("welcome");
   registry.addViewController("/help").setViewName("help");
   registry.addViewController("/404").setViewName("error_404");
   registry.addViewController("/403").setViewName("error_403");
   registry.addViewController("/405").setViewName("error_405");
   registry.addViewController("/500").setViewName("error_500");

   // The list goes on for 57 more lines
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;These mappings will not show up in the event listener (since there's no method handler I guess). So I had to update my listener to this :&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;@Log4j
@Component
public class EndpointsListener implements ApplicationListener&amp;lt;ContextRefreshedEvent&amp;gt; {

    private final HandlerMapping viewControllerHandlerMapping;

    public EndpointsListener(HandlerMapping viewControllerHandlerMapping) {
        this.viewControllerHandlerMapping = viewControllerHandlerMapping;
    }

    @SneakyThrows
    @Override
    public void onApplicationEvent(ContextRefreshedEvent event) {
        ApplicationContext applicationContext = event.getApplicationContext();
        List&amp;lt;Mapping&amp;gt; mappings = new ArrayList&amp;lt;&amp;gt;();
        for (Map.Entry&amp;lt;RequestMappingInfo, HandlerMethod&amp;gt; entry : applicationContext
                .getBean(RequestMappingHandlerMapping.class).getHandlerMethods().entrySet()) {
            RequestMappingInfo requestMappingInfo = entry.getKey();
            HandlerMethod handlerMethod = entry.getValue();
            Mapping mapping = new Mapping();
            mapping.setMethods(requestMappingInfo.getMethodsCondition().getMethods()
                    .stream().map(Enum::name).collect(Collectors.toSet()));
            mapping.setPatterns(requestMappingInfo.getPatternsCondition().getPatterns());
            Arrays.stream(handlerMethod.getMethodParameters()).forEach(methodParameter -&amp;gt; {
                    mapping.getParams().add(methodParameter.getParameter().getType().getSimpleName());
            });
            mappings.add(mapping);
        }

        ((SimpleUrlHandlerMapping) viewControllerHandlerMapping).getHandlerMap().forEach((s, o) -&amp;gt; {
            Mapping mapping = new Mapping();
            mapping.setMethods(Collections.singleton("GET"));
            mapping.setPatterns(Collections.singleton(s));
            mappings.add(mapping);
        });

        mappings.sort(Comparator.comparing(o -&amp;gt; o.getPatterns().stream().findFirst().orElse("")));
        log.info(new ObjectMapper().writeValueAsString(mappings));
    }

    @Data
    public class Mapping {
        private Set&amp;lt;String&amp;gt; patterns;
        private Set&amp;lt;String&amp;gt; methods;
        private List&amp;lt;String&amp;gt; params;

        public List&amp;lt;String&amp;gt; getParams(){
            if(params == null) {
                params = new ArrayList&amp;lt;&amp;gt;();
            }
            return params;

        }
    }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;By this, I will have a log of all the request mappings and their request parameter types. &lt;br&gt;
The code needs a bit of refactoring for sure:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Method parameters like HttpServletRequest or HttpSession should be ignored.&lt;/li&gt;
&lt;li&gt;Parameter names are not logged.&lt;/li&gt;
&lt;li&gt;Required status of parameters is not logged.&lt;/li&gt;
&lt;li&gt;PathVariables should be logged separately.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;The method handler could just give us parameter names like &lt;code&gt;"arg0"&lt;/code&gt;, &lt;code&gt;"arg1"&lt;/code&gt; and etc. But since our parameters are all annotated by &lt;code&gt;@RequestParam&lt;/code&gt; we can easily get their names by getting the parameter annotation. This way we could log if the parameter is required or not and if it has a default value. The final code looks like this :&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;/**
 * A listener to listen on {@link ContextRefreshedEvent}.
 */
@Log4j
@Component
public class EndpointsListener implements ApplicationListener&amp;lt;ContextRefreshedEvent&amp;gt; {
    /**
     * Provides access to all view controllers defined in {@link SpringConfig}.
     */
    private final HandlerMapping viewControllerHandlerMapping;

    /**
     * Constructor.
     *
     * @param viewControllerHandlerMapping View Controller Handler Mapping.
     */
    public EndpointsListener(HandlerMapping viewControllerHandlerMapping) {
        this.viewControllerHandlerMapping = viewControllerHandlerMapping;
    }

    /**
     * On context refresh, get all request handler mappings and create a list.
     * Also get the view controller mappings from {@link #viewControllerHandlerMapping} and add to the list.
     *
     * @param event A {@link ContextRefreshedEvent}.
     */
    @SneakyThrows
    @Override
    public void onApplicationEvent(ContextRefreshedEvent event) {
        ApplicationContext applicationContext = event.getApplicationContext();
        List&amp;lt;CustomMapping&amp;gt; mappings = new ArrayList&amp;lt;&amp;gt;();
        for (Map.Entry&amp;lt;RequestMappingInfo, HandlerMethod&amp;gt; entry : applicationContext
                .getBean(RequestMappingHandlerMapping.class).getHandlerMethods().entrySet()) {
            RequestMappingInfo requestMappingInfo = entry.getKey();
            HandlerMethod handlerMethod = entry.getValue();
            CustomMapping mapping = new CustomMapping();
            mapping.setMethods(requestMappingInfo.getMethodsCondition().getMethods()
                    .stream().map(Enum::name).collect(Collectors.toSet()));
            mapping.setPatterns(requestMappingInfo.getPatternsCondition().getPatterns());
            Arrays.stream(handlerMethod.getMethodParameters()).forEach(methodParameter -&amp;gt; {
                CustomParameter parameter = new CustomParameter();
                Annotation[] parameterAnnotations = methodParameter.getParameterAnnotations();
                Arrays.stream(parameterAnnotations).forEach(annotation -&amp;gt; {
                    if (annotation instanceof PathVariable) {
                        PathVariable pathVariable = (PathVariable) annotation;
                        mapping.getPathVariables()
                                .add(new CustomPathVariable(pathVariable.name(), pathVariable.required()));
                    } else if (annotation instanceof RequestParam) {
                        RequestParam requestParam = (RequestParam) annotation;
                        parameter.setName(requestParam.name());
                        String defaultValue = requestParam.defaultValue();
                        if (!defaultValue.equals(ValueConstants.DEFAULT_NONE)) {
                            parameter.setDefaultValue(defaultValue);
                        }
                        parameter.setRequired(requestParam.required());
                        parameter.setType(methodParameter.getParameter().getType().getSimpleName());
                        mapping.getParams().add(parameter);
                    }
                });
            });
            mappings.add(mapping);
        }

        ((SimpleUrlHandlerMapping) viewControllerHandlerMapping).getHandlerMap().forEach((s, o) -&amp;gt; {
            CustomMapping mapping = new CustomMapping();
            mapping.setMethods(Collections.singleton("GET"));
            mapping.setPatterns(Collections.singleton(s));
            mappings.add(mapping);
        });

        mappings.sort(Comparator.comparing(o -&amp;gt; o.getPatterns().stream().findFirst().orElse("")));
        log.info(new ObjectMapper().writeValueAsString(mappings));
    }

    /**
     * Custom mapping class.
     */
    @JsonInclude(JsonInclude.Include.NON_EMPTY)
    @Data
    public class CustomMapping {
        private Set&amp;lt;String&amp;gt; patterns;
        private Set&amp;lt;String&amp;gt; methods;
        private List&amp;lt;CustomParameter&amp;gt; params = new ArrayList&amp;lt;&amp;gt;();
        private List&amp;lt;CustomPathVariable&amp;gt; pathVariables = new ArrayList&amp;lt;&amp;gt;();
    }

    /**
     * Custom Parameter class
     */
    @JsonInclude(JsonInclude.Include.NON_NULL)
    @Data
    public class CustomParameter {
        private String name;
        private String type;
        private String defaultValue;
        private Boolean required;
    }

    /**
     * Custom path variable class.
     */
    @JsonInclude(JsonInclude.Include.NON_NULL)
    @AllArgsConstructor
    @Data
    public class CustomPathVariable {
        private String name;
        private Boolean required;
    }
}

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;But what if they are changed? What if we add a new controller the day after we declare our URLs to the security guys? So instead of logging the results, I will keep them as a list and write a rest controller for accessing them.&lt;/p&gt;

&lt;p&gt;The code is also available as a &lt;a href="https://gist.github.com/amaralani/2e310d0f2855c8f0a6c50724e5cab03a"&gt;gist&lt;/a&gt;.&lt;/p&gt;

</description>
      <category>java</category>
      <category>spring</category>
      <category>requestmapping</category>
      <category>applicationlistener</category>
    </item>
    <item>
      <title>Assertion vs Assumption when writing tests (JUnit)
</title>
      <dc:creator>Amir Maralani</dc:creator>
      <pubDate>Mon, 16 Nov 2020 07:27:23 +0000</pubDate>
      <link>https://dev.to/amaralani/assertion-vs-assumption-when-writing-tests-junit-4m36</link>
      <guid>https://dev.to/amaralani/assertion-vs-assumption-when-writing-tests-junit-4m36</guid>
      <description>&lt;p&gt;Most of the developers are familiar with the concept of assertion in test writing. &lt;em&gt;Assertion&lt;/em&gt; is the process of making sure some condition is met. Most of the times the condition is a kind of check for the result of the tested unit. For example an array being empty, of a variable being filled with the proper value. Check this example, let's write a simple calculator class. This class has two methods: &lt;code&gt;add&lt;/code&gt; and &lt;code&gt;multiply&lt;/code&gt;. &lt;code&gt;add&lt;/code&gt; method simply adds two integers and returns the result, but the &lt;code&gt;multiply&lt;/code&gt; method uses the add method for multiplication.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;
public class Calculator {

    public int add(int a, int b) {
        return a + b;
    }

    public int multiply(int a, int b) {
        int result = 0;
        for (int i = 0; i &amp;lt; b; i++) {
            result += add(result,a);
        }
        return result;
    }
}

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;For the add method my unit test would be like this :&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;@Test
public void testAdd() {
    int a = ThreadLocalRandom.current().nextInt();
    int b = ThreadLocalRandom.current().nextInt();
    int result = calculator.add(a, b);

    Assertions.assertEquals(a + b, result);
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;For any two given integers, the result of &lt;code&gt;add&lt;/code&gt; method should be equal to adding them together.&lt;br&gt;
My unit test for &lt;code&gt;multiply&lt;/code&gt; method would be like this:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;    @Test
    public void testMultiply() {
        int a = ThreadLocalRandom.current().nextInt();
        int b = ThreadLocalRandom.current().nextInt();

        int multiplicationResult = calculator.multiply(a, b);

        Assertions.assertEquals(a * b, multiplicationResult);
    }
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;It works, but there's something to note. We know that the &lt;code&gt;multiply&lt;/code&gt; method heavily relies on the &lt;code&gt;add&lt;/code&gt; method. If add is not working, there's no point in testing the &lt;code&gt;multiply&lt;/code&gt;. For our example, it would not hurt much but in real-world problems, it may affect test time and resources heavily. What can we do? We can use &lt;em&gt;Assumption&lt;/em&gt;.&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;@Test
public void testMultiply() {
    int a = ThreadLocalRandom.current().nextInt();
    int b = ThreadLocalRandom.current().nextInt();
    int additionResult = calculator.add(a, b);

    Assumptions.assumeTrue(a + b == additionResult);

    int multiplicationResult = calculator.multiply(a, b);

    Assertions.assertEquals(a * b, multiplicationResult);
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;When assuming, you check the prerequisites of the test, if they are not available or do not have the expected value, there's no point in continuing with the test. In the above example, we first make sure that the &lt;code&gt;add&lt;/code&gt; method is working properly.&lt;/p&gt;

&lt;p&gt;Why not just assert them? The difference is if the assertion fails the test will fail but if the assumption fails the test will be ignored. Although in many tests they are asserted, that's not the way it should be. We do not want to test the functionalities of other methods, but we want to be sure that they are working properly.&lt;/p&gt;

&lt;p&gt;If the tests are well written for all the parts of code, the part which makes the assumption fail would have proper tests that would fail.&lt;/p&gt;

&lt;p&gt;For example, if our add method is not working properly, the &lt;code&gt;testAdd&lt;/code&gt; would fail and the &lt;code&gt;testMultiply&lt;/code&gt; would be ignored.&lt;/p&gt;

</description>
      <category>java</category>
      <category>junit</category>
    </item>
  </channel>
</rss>
