<?xml version="1.0" encoding="UTF-8"?><rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>Testing &#8211; CodePills.com</title>
	<atom:link href="https://codepills.com/category/testing/feed/" rel="self" type="application/rss+xml" />
	<link>https://codepills.com</link>
	<description>Helping you make a better code</description>
	<lastBuildDate>Sat, 22 May 2021 17:02:42 +0000</lastBuildDate>
	<language>en-US</language>
	<sy:updatePeriod>
	hourly	</sy:updatePeriod>
	<sy:updateFrequency>
	1	</sy:updateFrequency>
	
	<item>
		<title>Verify method was called n-times with Mockito</title>
		<link>https://codepills.com/verify-method-was-called-n-times-with-mockito/</link>
					<comments>https://codepills.com/verify-method-was-called-n-times-with-mockito/#respond</comments>
		
		<dc:creator><![CDATA[Andrej Buday]]></dc:creator>
		<pubDate>Sat, 03 Apr 2021 15:31:10 +0000</pubDate>
				<category><![CDATA[Testing]]></category>
		<category><![CDATA[dependency injection]]></category>
		<category><![CDATA[Java]]></category>
		<category><![CDATA[mockito]]></category>
		<category><![CDATA[testing]]></category>
		<guid isPermaLink="false">https://codepills.com/?p=1206</guid>

					<description><![CDATA[Mockito Verify example for n-times calls using various verification modes. <a href="https://codepills.com/verify-method-was-called-n-times-with-mockito/">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
										<content:encoded><![CDATA[<p>This short article will explain how to <strong>verify</strong> that Mock&#8217; method was called n-times with the help of <strong>Mockito testing framework</strong>.</p>
<p><span id="more-1206"></span></p>
<h2>Introduction</h2>
<p>We often encounter the problem during testing that we do not care about the data correctness, as much as we care about correct algorithm flow. In this situations, we want to check if specific methods were hit and executed. Sometimes we need to go deeper and seek an answer on how often these methods were called or verify that the methods called at all.</p>
<p>The necessary method, which will help us in our testing quest, is called <a href="https://javadoc.io/static/org.mockito/mockito-core/3.9.0/org/mockito/Mockito.html#exact_verification" title="Mockito verify" target="_blank" rel="nofollow noopener">verify()</a> and is part of <strong>Mockito testing framework</strong>.</p>
<h2>Mockito verify verification options</h2>
<pre><code class="language-java">public static <T> T verify(T mock, VerificationMode mode)</code></pre>
<p><i>mock</i> is object of type <code>T</code> you are placing into the <code>verify()</code> method for verification. As a second method argument is <code>VerificationMode</code> <i>mode</i> variable, which describes how the <i>mock</i> should be verified. Possible verification modes are:</p>
<pre><code class="language-java">verify(mock, times(5)).someMethod("was called exactly five times");
verify(mock, never()).someMethod("was never called");
verify(mock, atLeast(5)).someMethod("was called at least five times");
verify(mock, atLeastOnce()).someMethod("was called at least once");
verify(mock, atMost(5)).someMethod("was called at most five times");</code></pre>
<p>There is also one special <code>VerificationMode</code> mode called <code>only()</code>. This mode verifies that no other method was called on the mock so far.</p>
<pre><code class="language-java">verify(mock, only()).someMethod("only someMethod was called");</code></pre>
<h2>Mockito verify verification modes in action </h2>
<p>In order to test individual verification modes, we will write a simple test. For testing purposes it will consist from two classes. (Both are inner private classes for <i>MockitoVerifyTest.java</i>.) First will be a fake class <code>Account</code> which trough dependency injection will use second class <code>Counter</code>. <code>Counter</code> class will be used as a <code>Mock</code> in our test.</p>
<p>Here is a <code>Counter</code> class:</p>
<pre><code class="language-java">private class Counter {

    private int counter;

    public Counter() {
        this.counter = 0;
    }

    public void increment() {
        this.counter++;
    }

    public void reset() {
        this.counter = 0;
    }

    public int getCount() {
        return this.counter;
    }
}</code></pre>
<p>And here is the <code>Account</code> class:</p>
<pre><code class="language-java">private class Account {

    private Counter counter;

    public Account(Counter counter) {
        this.counter = counter;
    }

    public void incrementCounter() {
        this.counter.increment();
    }

    public void resetCounter() {
        this.counter.reset();
    }

    public int getCounterValue() {
        return this.counter.getCount();
    }
}</code></pre>
<p>And finally, here is an exemplary test where you can see usage of individual verification modes:</p>
<pre><code class="language-java">import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.mockito.Mockito;
import org.mockito.junit.MockitoJUnitRunner;

import static org.mockito.Mockito.atLeast;
import static org.mockito.Mockito.atLeastOnce;
import static org.mockito.Mockito.atMost;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.only;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;

@RunWith(MockitoJUnitRunner.class)
public class MockitoVerifyTest {

    @Mock
    Counter counter;

    @Test
    public void testMockitoVerifyMethodCalls() {

        Account account = new Account(counter);

        // Verification using only() and atLeastOnce()
        account.incrementCounter();
        Mockito.verify(counter, only()).increment();
        Mockito.verify(counter, atLeastOnce()).increment();

        // Verification using times(X)
        for (int i = 0; i < 4; i++) {
            account.incrementCounter();
        }
        Mockito.verify(counter, times(5)).increment();

        // Verification using atLeast(X), atMost(X), never()
        for (int i = 0; i < 5; i++) {
            account.incrementCounter();
        }
        Mockito.verify(counter, atLeast(5)).increment();
        Mockito.verify(counter, atMost(10)).increment();
        Mockito.verify(counter, never()).getCount();
    }
}</code></pre>
<p>Let's discuss little but example code.</p>
<pre><code class="language-java">Account account = new Account(counter);

// Verification using only() and atLeastOnce()
account.incrementCounter();
Mockito.verify(counter, only()).increment();
Mockito.verify(counter, atLeastOnce()).increment();</code></pre>
<p>First, we will create new instance of <code>Account</code> class which trough dependency injection is injected with Mock instance of our <code>Counter</code> class.</p>
<p>As first we verify that there was no method, except <i>increment()</i> method, has been called on our mock at all. And as second verification, we will check that it was called at least once,</p>
<pre><code class="language-java">for (int i = 0; i < 4; i++) {
    account.incrementCounter();
}
Mockito.verify(counter, times(5)).increment();</code></pre>
<p>Now we call <i>incrementCounter()</i> method four more times, remember we already called it once, and we will check that it was mock method injected to instance was called <b>exactly</b> five times.</p>
<pre><code class="language-java">for (int i = 0; i < 5; i++) {
    account.incrementCounter();
}
Mockito.verify(counter, atLeast(5)).increment();
Mockito.verify(counter, atMost(10)).increment();
Mockito.verify(counter, never()).getCount();</code></pre>
<p>In the last section, we are incrementing the counter again five more times, and now we are checking if it was called <b>at least</b> five times and <b>at most</b> ten times.</p>
<p>On the last line we are checking method call for Mock' <i>getCount()</i> method that was <b>never</b> called.</p>
<h2>Conclusion</h2>
<p>This article contains a straightforward test on which we have demonstrated how to use Mockito <code>verify</code> method for mock' method call verification.</p>
<p>As always, you can find all our examples on our <a href="https://github.com/codekopf/tutorials-jvm/tree/master/testing-modules/mockito/" title="Tutorial JVM - Testing modules - Mockito" target="_blank" rel="nofollow noopener">GitHub project</a>!</p>
]]></content:encoded>
					
					<wfw:commentRss>https://codepills.com/verify-method-was-called-n-times-with-mockito/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>How to check if two lists are equal in Java</title>
		<link>https://codepills.com/how-to-check-if-two-lists-are-equal-in-java/</link>
					<comments>https://codepills.com/how-to-check-if-two-lists-are-equal-in-java/#respond</comments>
		
		<dc:creator><![CDATA[Andrej Buday]]></dc:creator>
		<pubDate>Thu, 01 Apr 2021 09:55:26 +0000</pubDate>
				<category><![CDATA[Testing]]></category>
		<category><![CDATA[assert list]]></category>
		<category><![CDATA[Java]]></category>
		<category><![CDATA[Java Collections]]></category>
		<category><![CDATA[Java List]]></category>
		<category><![CDATA[testing]]></category>
		<guid isPermaLink="false">https://codepills.com/?p=1202</guid>

					<description><![CDATA[A short article focused on a widespread problem in testing if two list instances are identical, or rather say if they contain the same elements in the same order. <a href="https://codepills.com/how-to-check-if-two-lists-are-equal-in-java/">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
										<content:encoded><![CDATA[<p>This short article will explain to you what List equality means and how to compare two <strong>Java lists</strong> against each other.</p>
<p><span id="more-1202"></span></p>
<h2>Introduction</h2>
<p>Checking list equality is a widespread problem; we often need to compare the list elements against each other. Comparison and assertion occur many times during the testing when we need to assert results with predefined expectations.</p>
<h2>Two lists equality</h2>
<p>At first, some might think, that for equality of two lists is conditioned by lists containing the same elements. This way of thinking is not entirely true. Single look into the Java documentations for <a href="https://docs.oracle.com/javase/8/docs/api/java/util/List.html#equals-java.lang.Object-" title="List equals" target="_blank" rel="nofollow noopener">List.equals()</a> method will uncover us true meaning of list equality:</p>
<blockquote><p>
    &#8230; two lists are defined to be equal if they contain the same elements in the same order.
</p></blockquote>
<p>Therefore, we need to compare the lists&#8217; elements mutually, but we also need to check the order of the elements in the lists reciprocally.</p>
<p>So first, let&#8217;s take a good look at how not to do a list equality check.</p>
<h2>Compare two list with the bruteforce</h2>
<p>Following lines of code are placed here only for demonstration purposes. For all cost, you must avoid such hideous brute force solution in your code.</p>
<pre><code class="language-java">private boolean compareLists(final List list1,final List list2) {
    if(list1.size() == list2.size()) {
        if(list1.isEmpty() && list2.isEmpty()) {
            return true;
        }
        for(int i = 0; i < list1.size(); i++) {
            if(!list1.get(i).equals(list2.get(i))) {
                return false;
            };
        }
        return true;
    }
    return false;
}</code></pre>
<p>The reason why to not use it in your code is that this code is basically <code>List</code> interface implementation of the <code>equal()</code> method. Therefore all you need to use for comparing two lists is to call <code>equal()</code> method.</p>
<pre><code class="language-java">private boolean compareLists(final List list1,final List list2) {
    return list1.equals(list2);
}</code></pre>
<p><b>Interface method definition ensures</b> that the equals method works through different implementations of the <strong>List</strong> interface in a same way.</p>
<h2>Framework usage</h2>
<p>For testing purposes, it is probably better to use some of the available <strong>Java frameworks for testing</strong>, which can give us more options in List testing.</p>
<p>In our examples, we will play with the following code snippet based on user entities belonging to different groups. We will compare lists are figure out if all users are members of all groups.</p>
<pre><code class="language-java">List<String> users = Arrays.asList("John Doe", "Tom Smith", "Paul Iron", "George Silver");
List<String> moderators = Arrays.asList("John Doe", "Tom Smith", "Paul Iron", "George Silver");
List<String> admins = Arrays.asList("John Doe", "Tom Smith", "Paul Iron", "George Silver");</code></pre>
<h3>JUnit</h3>
<p>Rather than using and printing equals for tests, it is better to use assert methods. <strong>JUnit</strong> testing framework offers us three suitable ways for list equality assertion.</p>
<ul>
<li><code>assertEquals(expected, actual)</code> - Asserts that two objects are equal. If they are not, an <code>AssertionError</code> without a message is thrown. If <i>expected</i> and <i>actual</i> are <code>null</code>, they are considered equal.</li>
<li><code>assertNotSame(unexpected, actual)</code> - Asserts that two objects do not refer to the same object. If they do refer to the same object, an <code>AssertionError</code> without a message is thrown.</li>
<li><code>assertNotEquals(unexpected, actual)</code> - Asserts that two objects are not equals. If they are, an <code>AssertionError</code> without a message is thrown. If <i>unexpected</i> and <i>actual</i> are <code>null</code>, they are considered equal.</li>
</ul>
<pre><code class="language-java">@Test
public void testJUnitListAsserts() throws Exception {
    Assert.assertEquals(users, moderators);
    Assert.assertNotSame(users, moderators);
    Assert.assertNotEquals(users, admins);
}</code></pre>
<h2>Conclusion</h2>
<p>This article has shown you how not to do list assertion and explain how to check and assert two lists equality.</p>
<p>As always, you can find all our examples on our <a href="https://github.com/codekopf/tutorials-jvm/tree/master/testing-modules/junit-basics/" title="Tutorial JVM - Testing Modules - JUnit Basics" target="_blank" rel="nofollow noopener">GitHub project</a>!</p>
]]></content:encoded>
					
					<wfw:commentRss>https://codepills.com/how-to-check-if-two-lists-are-equal-in-java/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>3 basic mistakes for NullPointerException when Mock</title>
		<link>https://codepills.com/3-basic-mistakes-for-nullpointerexception-when-mock/</link>
					<comments>https://codepills.com/3-basic-mistakes-for-nullpointerexception-when-mock/#comments</comments>
		
		<dc:creator><![CDATA[Andrej Buday]]></dc:creator>
		<pubDate>Thu, 10 May 2018 12:00:47 +0000</pubDate>
				<category><![CDATA[Testing]]></category>
		<category><![CDATA[mock]]></category>
		<category><![CDATA[mocking]]></category>
		<category><![CDATA[mockito]]></category>
		<category><![CDATA[Spring]]></category>
		<guid isPermaLink="false">http://codepills.com/?p=958</guid>

					<description><![CDATA[This article is a shortlist of the three most common reasons why you get NullPointerException in your tests. <a href="https://codepills.com/3-basic-mistakes-for-nullpointerexception-when-mock/">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
										<content:encoded><![CDATA[<p>You might get <code>NullPointerException</code> exception when you try to mock object in your tests. This article is a shortlist of the three most common reasons why this might be happening.</p>
<p><span id="more-958"></span></p>
<p>Here is a working example of DocumentRepositoryTest class for reference:</p>
<pre><code class="language-java">@RunWith(MockitoJUnitRunner.class)
public final class DocumentRepositoryTest {

    @Mock
    private DocumentRepository documentRepository;

    @Test
    public void testConvertToNewDocument() {
        String paperColor = new String("white");
        Mockito.when(this.documentRepository.getPaperColor()).thenReturn(paperColor);
        String color = this.documentRepository.getDocumentColor();
        Assert.assertThat(color, is(new String("white"));
    }
}</code></pre>
<p>DocumentRepositoryTest class is mocking <code>documentRepository</code> object.</p>
<p>So you are running your test and suddenly you see <code>NullPointerException</code>:</p>
<pre><code class="language-bash">java.lang.NullPointerException at com.your.custom.clazz.Method.insertTest(CustomServiceTest.java:50)</code></pre>
<p>You looked it up, and it seems your test is written correctly. So what might be a problem if you know how the mocking works?</p>
<p>If you are sure by your mocking skills, the issue will be probably somewhere else. And most likely very trivial. Here is a list of 3 things you should check out.</p>
<p><strong>1. Return something for your Mock.</strong></p>
<p>Most likely, you mistyped returning function. You probably wanted to return the value for the mocked object. So instead of <code>when-thenReturn</code> , you might type just <code>when-then</code>. Maybe it was IntelliSense. Maybe you did it accidentally. But for sure, <code>NullPointerException</code> happened because you want something which is not there. Debug and check if you are returning something.</p>
<p><strong>2. Specify Mockito running class</strong></p>
<p>Don&#8217;t forget to annotate your Testing class with <code>@RunWith(MockitoJUnitRunner.class)</code>. Most of the people just forget to specify the test runner, running class for mocking.</p>
<p><strong>3. You need to annotate the mocking object with the <code>@Mock</code> annotation</strong></p>
<p>If you want to mock an object, you need to annotate the object with <code>@Mock</code> annotation.</p>
]]></content:encoded>
					
					<wfw:commentRss>https://codepills.com/3-basic-mistakes-for-nullpointerexception-when-mock/feed/</wfw:commentRss>
			<slash:comments>5</slash:comments>
		
		
			</item>
	</channel>
</rss>
