<?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>mockito &#8211; CodePills.com</title>
	<atom:link href="https://codepills.com/tag/mockito/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>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>
