<?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>Hamcrest &#8211; My Shitty Code</title>
	<atom:link href="https://myshittycode.com/tag/hamcrest/feed/" rel="self" type="application/rss+xml" />
	<link>https://myshittycode.com</link>
	<description>Embracing the Messiness in Search of Epic Solutions</description>
	<lastBuildDate>Fri, 06 Jan 2023 17:19:23 +0000</lastBuildDate>
	<language>en-US</language>
	<sy:updatePeriod>
	hourly	</sy:updatePeriod>
	<sy:updateFrequency>
	1	</sy:updateFrequency>
	<generator>https://wordpress.org/?v=6.9.1</generator>

<image>
	<url>https://myshittycode.com/wp-content/uploads/2022/04/cropped-icon-32x32.png</url>
	<title>Hamcrest &#8211; My Shitty Code</title>
	<link>https://myshittycode.com</link>
	<width>32</width>
	<height>32</height>
</image> 
<site xmlns="com-wordpress:feed-additions:1">205304208</site>	<item>
		<title>How to Unit Test Spring MVC Controller</title>
		<link>https://myshittycode.com/2013/10/23/how-to-unit-test-spring-mvc-controller/</link>
					<comments>https://myshittycode.com/2013/10/23/how-to-unit-test-spring-mvc-controller/#comments</comments>
		
		<dc:creator><![CDATA[Shitty Author]]></dc:creator>
		<pubDate>Wed, 23 Oct 2013 20:23:01 +0000</pubDate>
				<category><![CDATA[Programming Language]]></category>
		<category><![CDATA[Hamcrest]]></category>
		<category><![CDATA[Java]]></category>
		<category><![CDATA[Maven]]></category>
		<category><![CDATA[Mockito]]></category>
		<category><![CDATA[Spring MVC Test Framework]]></category>
		<category><![CDATA[Unit Testing]]></category>
		<guid isPermaLink="false">http://myshittycode.com/?p=170</guid>

					<description><![CDATA[<p>SCENARIO Let&#8217;s assume we have the following controller that needs to be tested:- SOLUTION 1: &#8220;Works but It Won&#8217;t Get You the Promotion&#8221; This working solution relies on:- While this solution works, but it has a few problems. This test case strictly tests the actual controller API, but it completely disregards the URI and request [&#8230;]</p>
<p>The post <a rel="nofollow" href="https://myshittycode.com/2013/10/23/how-to-unit-test-spring-mvc-controller/">How to Unit Test Spring MVC Controller</a> appeared first on <a rel="nofollow" href="https://myshittycode.com">My Shitty Code</a>.</p>
]]></description>
										<content:encoded><![CDATA[
<h2 class="wp-block-heading">SCENARIO</h2>



<p>Let&#8217;s assume we have the following controller that needs to be tested:-</p>


<div class="wp-block-syntaxhighlighter-code "><pre class="brush: java; title: ; notranslate">
@Controller
@RequestMapping(value = &quot;/person&quot;)
public class PersonController {

    private PersonService personService;

    @Autowired
    public PersonController(PersonService personService) {
        this.personService = personService;
    }

    @RequestMapping(value = &quot;/{id}&quot;, method = RequestMethod.GET)
    public String getPerson(@PathVariable Long id, Model model) {
        model.addAttribute(&quot;personData&quot;, personService.getPerson(id));
        return &quot;personPage&quot;;
    }
}
</pre></div>


<h2 class="wp-block-heading">SOLUTION 1: <em>&#8220;Works but It Won&#8217;t Get You the Promotion&#8221;</em></h2>



<p>This working solution relies on:-</p>



<ul class="wp-block-list">
<li>JUnit &#8211; General unit test framework.</li>



<li>Mockito &#8211; To mock <b>PersonService</b>.</li>
</ul>


<div class="wp-block-syntaxhighlighter-code "><pre class="brush: java; title: ; notranslate">
public class PersonControllerTest {

    @Test
    public void testGetPerson() {

        PersonService personService = mock(PersonService.class);

        when(personService.getPerson(1L)).thenReturn(new Person(1L, &quot;Chuck&quot;));

        PersonController controller = new PersonController(personService);

        Model model = new ExtendedModelMap();

        String view = controller.getPerson(1L, model);

        assertEquals(&quot;View name&quot;, &quot;personPage&quot;, view);

        Person actualPerson = (Person) model.asMap().get(&quot;personData&quot;);

        assertEquals(&quot;matching ID&quot;, Long.valueOf(1), actualPerson.getId());
        assertEquals(&quot;matching Name&quot;, &quot;Chuck&quot;, actualPerson.getName());
    }
}
</pre></div>


<p>While this solution works, but it has a few problems. This test case strictly tests the actual controller API, but it completely disregards the URI and request method (GET, POST, PUT, DELETE, etc). For instance:-</p>



<ul class="wp-block-list">
<li>What if the URI has a typo ( <b>/persn/1</b> ) or it is not properly constructed ( <b>/person/donkey-kong</b> )?</li>



<li>What if the request method should be a <b>POST</b> but we accidentally used a <b>GET</b>?</li>
</ul>



<h2 class="wp-block-heading">SOLUTION 2: <em>&#8220;A Mind Blowing Solution that Still Won&#8217;t Get You the Promotion but You Feel So Invincible That You Feel Compelled to Flip a Table Over&#8221;</em></h2>



<p>This better solution relies on:-</p>



<ul class="wp-block-list">
<li>JUnit &#8211; General unit test framework.</li>



<li>Mockito &#8211; To mock <b>PersonService</b>.</li>



<li>Spring MVC Test Framework &#8211; To properly test the controller.</li>



<li>Hamcrest &#8211; To clean way to assert the actual result is correct.</li>
</ul>


<div class="wp-block-syntaxhighlighter-code "><pre class="brush: java; title: ; notranslate">
@RunWith(SpringJUnit4ClassRunner.class)
// This XML configuration basically enable component scanning.
// You could have used @Configuration and @ComponentScan to do the same thing.
@ContextConfiguration({&quot;classpath*:spring-test.xml&quot;})
public class PersonControllerTest {

    @Mock
    private PersonService personService;

    @InjectMocks
    private PersonController personController;

    private MockMvc mockMvc;

    @Before
    public void setup() {
        MockitoAnnotations.initMocks(this);
        mockMvc = MockMvcBuilders.standaloneSetup(personController).build();
    }

    @Test
    public void testGetPerson() throws Exception {
        when(personService.getPerson(1L)).thenReturn(new Person(1L, &quot;Chuck&quot;));

        mockMvc.perform(get(&quot;/person/{id}&quot;, 1L))
                .andExpect(status().isOk())
                .andExpect(view().name(&quot;personPage&quot;))
                .andExpect(model().attribute(&quot;personData&quot;,
                                             allOf(hasProperty(&quot;id&quot;, is(1L)),
                                                   hasProperty(&quot;name&quot;, is(&quot;Chuck&quot;)))));
    }
}
</pre></div>


<p>Basically object that is annotated with <b>@Mock</b> will get injected into object that is annotated with <b>InjectMocks</b>. Then, we rely on Spring MVC Test Framework&#8217;s <b>MockMvc</b> to test our controller in a very clean and detailed fashion.</p>



<p>Okay, you may flip a table over now&#8230;</p>



<h3 class="wp-block-heading">By the way&#8230;</h3>



<p>You need at least Spring 3.2 to use <b>MockMvc</b>.</p>


<div class="wp-block-syntaxhighlighter-code "><pre class="brush: xml; title: ; notranslate">
&lt;dependency&gt;
	&lt;groupid&gt;org.springframework&lt;/groupid&gt;
	&lt;artifactid&gt;spring-test&lt;/artifactid&gt;
	&lt;version&gt;3.2.4.RELEASE&lt;/version&gt;
	&lt;scope&gt;test&lt;/scope&gt;
&lt;/dependency&gt;
</pre></div>


<p>If you are using an older Mockito version, you will get this error:-</p>


<div class="wp-block-syntaxhighlighter-code "><pre class="brush: plain; title: ; notranslate">
org.mockito.exceptions.base.MockitoException: Field &#039;personController&#039; annotated with @InjectMocks is null.
Please make sure the instance is created *before* MockitoAnnotations.initMocks();
Example of correct usage:
   class SomeTest {
      @InjectMocks private Foo foo = new Foo();

      @Before public void setUp() {
         MockitoAnnotations.initMock(this);
</pre></div>


<p>Upgrading Mockito to the latest version will fix this error:-</p>


<div class="wp-block-syntaxhighlighter-code "><pre class="brush: xml; title: ; notranslate">
&lt;dependency&gt;
	&lt;groupid&gt;org.mockito&lt;/groupid&gt;
	&lt;artifactid&gt;mockito-core&lt;/artifactid&gt;
	&lt;version&gt;1.9.5&lt;/version&gt;
	&lt;scope&gt;test&lt;/scope&gt;
&lt;/dependency&gt;
</pre></div><p>The post <a rel="nofollow" href="https://myshittycode.com/2013/10/23/how-to-unit-test-spring-mvc-controller/">How to Unit Test Spring MVC Controller</a> appeared first on <a rel="nofollow" href="https://myshittycode.com">My Shitty Code</a>.</p>
]]></content:encoded>
					
					<wfw:commentRss>https://myshittycode.com/2013/10/23/how-to-unit-test-spring-mvc-controller/feed/</wfw:commentRss>
			<slash:comments>5</slash:comments>
		
		
		<post-id xmlns="com-wordpress:feed-additions:1">170</post-id>	</item>
	</channel>
</rss>

<!--
Performance optimized by W3 Total Cache. Learn more: https://www.boldgrid.com/w3-total-cache/?utm_source=w3tc&utm_medium=footer_comment&utm_campaign=free_plugin

Page Caching using Disk: Enhanced 
Lazy Loading (feed)
Database Caching using Disk

Served from: myshittycode.com @ 2026-02-21 10:52:44 by W3 Total Cache
-->