<?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>Unit Testing &#8211; My Shitty Code</title>
	<atom:link href="https://myshittycode.com/tag/unit-testing/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>Unit Testing &#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>Spring: Component Scan Selected Classes</title>
		<link>https://myshittycode.com/2017/03/25/spring-component-scan-selected-classes/</link>
					<comments>https://myshittycode.com/2017/03/25/spring-component-scan-selected-classes/#respond</comments>
		
		<dc:creator><![CDATA[Shitty Author]]></dc:creator>
		<pubDate>Sat, 25 Mar 2017 21:13:57 +0000</pubDate>
				<category><![CDATA[Programming Language]]></category>
		<category><![CDATA[Groovy]]></category>
		<category><![CDATA[Spring]]></category>
		<category><![CDATA[Unit Testing]]></category>
		<guid isPermaLink="false">http://myshittycode.com/?p=917</guid>

					<description><![CDATA[<p>PROBLEM Let&#8217;s assume we have a package with the following classes where each class is either annotated with Spring&#8217;s @Service, @Component, @Controller or @Repository. When writing unit test, we want Spring to component scan class A and class B. SOLUTION Before we begin, we configure Log4j to log Spring in debug level. Step 1 If [&#8230;]</p>
<p>The post <a rel="nofollow" href="https://myshittycode.com/2017/03/25/spring-component-scan-selected-classes/">Spring: Component Scan Selected Classes</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">PROBLEM</h2>



<p>Let&#8217;s assume we have a package with the following classes where each class is either annotated with Spring&#8217;s <b>@Service</b>, <b>@Component</b>, <b>@Controller</b> or <b>@Repository</b>.</p>


<div class="wp-block-syntaxhighlighter-code "><pre class="brush: plain; title: ; notranslate">
app
├── A.groovy
├── B.groovy
├── C.groovy
├── D.groovy
└── E.groovy
</pre></div>


<p>When writing unit test, we want Spring to component scan class A and class B.</p>



<h2 class="wp-block-heading">SOLUTION</h2>



<p>Before we begin, we configure Log4j to log Spring in debug level.</p>


<div class="wp-block-syntaxhighlighter-code "><pre class="brush: xml; title: ; notranslate">
&lt;logger name=&quot;org.springframework&quot;&gt;
    &lt;level value=&quot;debug&quot;&gt;
&lt;/level&gt;&lt;/logger&gt;
</pre></div>


<h3 class="wp-block-heading">Step 1</h3>



<p>If we configure the test class like this&#8230;</p>


<div class="wp-block-syntaxhighlighter-code "><pre class="brush: groovy; highlight: [5]; title: ; notranslate">
@ContextConfiguration
class ASpec extends Specification {
    @Configuration
    @ComponentScan(
            basePackageClasses = &#x5B;A]
	)
    static class TestConfig {
    }

    def &quot;...&quot;() {
        // ...
    }
}
</pre></div>


<p>It will scan all Spring components that reside in the same package as class A.</p>



<p>Debugging log:-</p>


<div class="wp-block-syntaxhighlighter-code "><pre class="brush: plain; title: ; notranslate">
&#x5B;DEBUG] &#x5B;ClassPathBeanDefinitionScanner] &#x5B;findCandidateComponents:294] - Identified candidate component class: file &#x5B;/path/target/classes/app/A.class]
&#x5B;DEBUG] &#x5B;ClassPathBeanDefinitionScanner] &#x5B;findCandidateComponents:294] - Identified candidate component class: file &#x5B;/path/target/classes/app/B.class]
&#x5B;DEBUG] &#x5B;ClassPathBeanDefinitionScanner] &#x5B;findCandidateComponents:294] - Identified candidate component class: file &#x5B;/path/target/classes/app/C.class]
&#x5B;DEBUG] &#x5B;ClassPathBeanDefinitionScanner] &#x5B;findCandidateComponents:294] - Identified candidate component class: file &#x5B;/path/target/classes/app/D.class]
&#x5B;DEBUG] &#x5B;ClassPathBeanDefinitionScanner] &#x5B;findCandidateComponents:294] - Identified candidate component class: file &#x5B;/path/target/classes/app/E.class]
</pre></div>


<h3 class="wp-block-heading">Step 2</h3>



<p>We can set <b>includeFilters</b> to include just class A and class B&#8230;</p>


<div class="wp-block-syntaxhighlighter-code "><pre class="brush: groovy; highlight: [6]; title: ; notranslate">
@ContextConfiguration
class ASpec extends Specification {
    @Configuration
    @ComponentScan(
            basePackageClasses = &#x5B;A],
            includeFilters = &#x5B;@ComponentScan.Filter(type = FilterType.ASSIGNABLE_TYPE, value = &#x5B;A, B])]
	)
    static class TestConfig {
    }

    def &quot;...&quot;() {
        // ...
    }
}
</pre></div>


<p>&#8230; but it doesn&#8217;t do anything.</p>



<p>Debugging log:-</p>


<div class="wp-block-syntaxhighlighter-code "><pre class="brush: plain; title: ; notranslate">
&#x5B;DEBUG] &#x5B;ClassPathBeanDefinitionScanner] &#x5B;findCandidateComponents:294] - Identified candidate component class: file &#x5B;/path/target/classes/app/A.class]
&#x5B;DEBUG] &#x5B;ClassPathBeanDefinitionScanner] &#x5B;findCandidateComponents:294] - Identified candidate component class: file &#x5B;/path/target/classes/app/B.class]
&#x5B;DEBUG] &#x5B;ClassPathBeanDefinitionScanner] &#x5B;findCandidateComponents:294] - Identified candidate component class: file &#x5B;/path/target/classes/app/C.class]
&#x5B;DEBUG] &#x5B;ClassPathBeanDefinitionScanner] &#x5B;findCandidateComponents:294] - Identified candidate component class: file &#x5B;/path/target/classes/app/D.class]
&#x5B;DEBUG] &#x5B;ClassPathBeanDefinitionScanner] &#x5B;findCandidateComponents:294] - Identified candidate component class: file &#x5B;/path/target/classes/app/E.class]
</pre></div>


<h3 class="wp-block-heading">Step 3</h3>



<p>To fix this, we set <b>useDefaultFilters</b> to false to disable any automatic detection of classes annotated with Spring&#8217;s <b>@Service</b>, <b>@Component</b>, <b>@Controller</b> or <b>@Repository</b>.</p>


<div class="wp-block-syntaxhighlighter-code "><pre class="brush: groovy; highlight: [6]; title: ; notranslate">
@ContextConfiguration
class ASpec extends Specification {
    @Configuration
    @ComponentScan(
            basePackageClasses = &#x5B;A],
            useDefaultFilters = false,
            includeFilters = &#x5B;@ComponentScan.Filter(type = FilterType.ASSIGNABLE_TYPE, value = &#x5B;A, B])]
    )
    static class TestConfig {
    }

    def &quot;...&quot;() {
        // ...
    }
}
</pre></div>


<p>Now, we get the intended behavior.</p>



<p>Debugging log:-</p>


<div class="wp-block-syntaxhighlighter-code "><pre class="brush: plain; title: ; notranslate">
&#x5B;DEBUG] &#x5B;ClassPathBeanDefinitionScanner] &#x5B;findCandidateComponents:294] - Identified candidate component class: file &#x5B;/path/target/classes/app/A.class]
&#x5B;DEBUG] &#x5B;ClassPathBeanDefinitionScanner] &#x5B;findCandidateComponents:294] - Identified candidate component class: file &#x5B;/path/target/classes/app/B.class]
</pre></div><p>The post <a rel="nofollow" href="https://myshittycode.com/2017/03/25/spring-component-scan-selected-classes/">Spring: Component Scan Selected Classes</a> appeared first on <a rel="nofollow" href="https://myshittycode.com">My Shitty Code</a>.</p>
]]></content:encoded>
					
					<wfw:commentRss>https://myshittycode.com/2017/03/25/spring-component-scan-selected-classes/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
		<post-id xmlns="com-wordpress:feed-additions:1">917</post-id>	</item>
		<item>
		<title>Java: Promoting Testability by Having Enum Implementing an Interface</title>
		<link>https://myshittycode.com/2014/08/18/java-promoting-testability-by-having-enum-implementing-an-interface/</link>
					<comments>https://myshittycode.com/2014/08/18/java-promoting-testability-by-having-enum-implementing-an-interface/#comments</comments>
		
		<dc:creator><![CDATA[Shitty Author]]></dc:creator>
		<pubDate>Mon, 18 Aug 2014 23:18:35 +0000</pubDate>
				<category><![CDATA[Programming Language]]></category>
		<category><![CDATA[Java]]></category>
		<category><![CDATA[Unit Testing]]></category>
		<guid isPermaLink="false">http://myshittycode.com/?p=561</guid>

					<description><![CDATA[<p>OVERVIEW This post illustrates how we can easily write a better test case without polluting our production code with non-production code by performing a minor refactoring to the production code. PROBLEM Let&#8217;s assume we have a simple Data Reader that reads all the lines of a given algorithm data file and returns them:- This API [&#8230;]</p>
<p>The post <a rel="nofollow" href="https://myshittycode.com/2014/08/18/java-promoting-testability-by-having-enum-implementing-an-interface/">Java: Promoting Testability by Having Enum Implementing an Interface</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">OVERVIEW</h2>



<p>This post illustrates how we can easily write a better test case without polluting our production code with non-production code by performing a minor refactoring to the production code.</p>



<h2 class="wp-block-heading">PROBLEM</h2>



<p>Let&#8217;s assume we have a simple Data Reader that reads all the lines of a given algorithm data file and returns them:-</p>


<div class="wp-block-syntaxhighlighter-code "><pre class="brush: java; title: ; notranslate">
public class DataReader {
    public List&lt;string&gt; getDataLines(AlgorithmEnum algorithm) {
        // we have `StS-data.txt`, `CtE-data.txt` and `TtI-data.txt` under `src/main/resources` dir
        String fileName = String.format(&quot;%s-data.txt&quot;, algorithm.getShortName());
        Scanner scanner = new Scanner(getClass().getClassLoader().getResourceAsStream(fileName));

        List&lt;string&gt; list = new ArrayList&lt;string&gt;();

        while (scanner.hasNextLine()) {
            list.add(scanner.nextLine());
        }

        return list;
    }
}
</pre></div>


<p>This API accepts an <b>AlgorithmEnum</b> and it looks something like this:-</p>


<div class="wp-block-syntaxhighlighter-code "><pre class="brush: java; title: ; notranslate">
public enum AlgorithmEnum {
    SKIN_TO_SKIN(&quot;StS&quot;),
    CLOSURE_TO_EXIT(&quot;CtE&quot;),
    TIME_TO_INCISION(&quot;TtI&quot;);

    private String shortName;

    AlgorithmEnum(String shortName) {
        this.shortName = shortName;
    }

    public String getShortName() {
        return shortName;
    }
}
</pre></div>


<p>Let&#8217;s assume each algorithm data file has millions of data lines.</p>



<p>So, how do we test this code?</p>



<h2 class="wp-block-heading">SOLUTION 1: Asserting Actual Line Count == Expected Line Count</h2>



<p>One straightforward way is to:-</p>



<ul class="wp-block-list">
<li>Pass in one of the Enum constants (<b>AlgorithmEnum.SKIN_TO_SKIN</b>, etc) into <b>DataReader.getDataLines(..)</b></li>



<li>Get the actual line counts</li>



<li>Assert the actual line counts against the expected line counts</li>
</ul>


<div class="wp-block-syntaxhighlighter-code "><pre class="brush: java; title: ; notranslate">
public class DataReaderTest {
    @Test
    public void testGetDataLines() {
        List&lt;string&gt; lines = new DataReader().getDataLines(AlgorithmEnum.SKIN_TO_SKIN);
        assertThat(lines, hasSize(7500));
    }
}
</pre></div>


<p>This is a pretty weak test because we only check the line counts. Since we are dealing with a lot of data lines, it becomes impossible to verify the correctness of each data line.</p>



<h2 class="wp-block-heading">SOLUTION 2: Adding a Test Constant to <b>AlgorithmEnum</b></h2>



<p>Another approach is to add a test constant to <b>AlgorithmEnum</b>:-</p>


<div class="wp-block-syntaxhighlighter-code "><pre class="brush: java; highlight: [6,7]; title: ; notranslate">
public enum AlgorithmEnum {
    SKIN_TO_SKIN(&quot;StS&quot;),
    CLOSURE_TO_EXIT(&quot;CtE&quot;),
    TIME_TO_INCISION(&quot;TtI&quot;),

    // added a constant for testing purpose
    TEST_ABC(&quot;ABC&quot;);

    private String shortName;

    AlgorithmEnum(String shortName) {
        this.shortName = shortName;
    }

    public String getShortName() {
        return shortName;
    }
}
</pre></div>


<p>Now, we can easily test the code with our test data stored at <b>src/test/resources/ABC-data.txt</b>:-</p>


<div class="wp-block-syntaxhighlighter-code "><pre class="brush: java; title: ; notranslate">
public class DataReaderTest {
    @Test
    public void testGetDataLines() {
        List&lt;string&gt; lines = new DataReader().getDataLines(AlgorithmEnum.TEST_ABC);
        assertThat(lines, is(Arrays.asList(&quot;line 1&quot;, &quot;line 2&quot;, &quot;line 3&quot;)));
    }
}
</pre></div>


<p>While this approach works, we pretty much polluted our production code with non-production code, which may become a maintenance nightmare as the project grows larger in the future.</p>



<h2 class="wp-block-heading">SOLUTION 3: <b>AlgorithmEnum</b> Implements an Interface</h2>



<p>Instead of writing a mediocre test case or polluting the production code with non-production code, we can perform a minor refactoring to our existing production code.</p>



<p>First, we create a simple interface:-</p>


<div class="wp-block-syntaxhighlighter-code "><pre class="brush: java; title: ; notranslate">
public interface Algorithm {
    String getShortName();
}
</pre></div>


<p>Then, we have <b>AlgorithmEnum</b> to implement <b>Algorithm</b>:-</p>


<div class="wp-block-syntaxhighlighter-code "><pre class="brush: java; highlight: [1]; title: ; notranslate">
public enum AlgorithmEnum implements Algorithm {
    SKIN_TO_SKIN(&quot;StS&quot;),
    CLOSURE_TO_EXIT(&quot;CtE&quot;),
    TIME_TO_INCISION(&quot;TtI&quot;);


    private String shortName;

    AlgorithmEnum(String shortName) {
        this.shortName = shortName;
    }

    public String getShortName() {
        return shortName;
    }
}
</pre></div>


<p>Now, instead of passing <b>AlgorithmEnum</b> into <b>getDataLines(&#8230;)</b>, we will pass in <b>Algorithm</b> interface.</p>


<div class="wp-block-syntaxhighlighter-code "><pre class="brush: java; highlight: [2]; title: ; notranslate">
public class DataReader {
    public List&lt;string&gt; getDataLines(Algorithm algorithm) {
        String fileName = String.format(&quot;%s-data.txt&quot;, algorithm.getShortName());
        Scanner scanner = new Scanner(getClass().getClassLoader().getResourceAsStream(fileName));


        List&lt;string&gt; list = new ArrayList&lt;string&gt;();

        while (scanner.hasNextLine()) {
            list.add(scanner.nextLine());
        }

        return list;
    }
}
</pre></div>


<p>With these minor changes, we can easily unit test the code with our mock data stored under <b>src/test/resources</b> directory.</p>


<div class="wp-block-syntaxhighlighter-code "><pre class="brush: java; title: ; notranslate">
public class DataReaderTest {
    @Test
    public void testGetDataLines() {
        List&lt;string&gt; lines = new DataReader().getDataLines(new Algorithm() {
            @Override
            public String getShortName() {
                // we have `ABC-data.txt` under `src/test/resources` dir
                return &quot;ABC&quot;;
            }
        });

        assertThat(lines, is(Arrays.asList(&quot;line 1&quot;, &quot;line 2&quot;, &quot;line 3&quot;)));
    }
}
</pre></div><p>The post <a rel="nofollow" href="https://myshittycode.com/2014/08/18/java-promoting-testability-by-having-enum-implementing-an-interface/">Java: Promoting Testability by Having Enum Implementing an Interface</a> appeared first on <a rel="nofollow" href="https://myshittycode.com">My Shitty Code</a>.</p>
]]></content:encoded>
					
					<wfw:commentRss>https://myshittycode.com/2014/08/18/java-promoting-testability-by-having-enum-implementing-an-interface/feed/</wfw:commentRss>
			<slash:comments>1</slash:comments>
		
		
		<post-id xmlns="com-wordpress:feed-additions:1">561</post-id>	</item>
		<item>
		<title>MockMvc : Circular view path [view]: would dispatch back to the current handler URL [/view] again</title>
		<link>https://myshittycode.com/2014/01/17/mockmvc-circular-view-path-view-would-dispatch-back-to-the-current-handler-url-view-again/</link>
					<comments>https://myshittycode.com/2014/01/17/mockmvc-circular-view-path-view-would-dispatch-back-to-the-current-handler-url-view-again/#comments</comments>
		
		<dc:creator><![CDATA[Shitty Author]]></dc:creator>
		<pubDate>Fri, 17 Jan 2014 12:13:19 +0000</pubDate>
				<category><![CDATA[Programming Language]]></category>
		<category><![CDATA[Spring MVC]]></category>
		<category><![CDATA[Spring MVC Test Framework]]></category>
		<category><![CDATA[Unit Testing]]></category>
		<guid isPermaLink="false">http://myshittycode.com/?p=332</guid>

					<description><![CDATA[<p>PROBLEM Let&#8217;s assume we want to test this controller:- Here&#8217;s the test file:- When executing this test, we get the following error:- SOLUTION The reason this is happening is because the uri &#8220;/help&#8221; matches the returned view name &#8220;help&#8221; and we didn&#8217;t set a ViewResolver when constructing the standalone MockMvc. Since MockMvcBuilders.standaloneSetup(...) doesn&#8217;t load Spring [&#8230;]</p>
<p>The post <a rel="nofollow" href="https://myshittycode.com/2014/01/17/mockmvc-circular-view-path-view-would-dispatch-back-to-the-current-handler-url-view-again/">MockMvc : Circular view path [view]: would dispatch back to the current handler URL [/view] again</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">PROBLEM</h2>



<p>Let&#8217;s assume we want to test this controller:-</p>


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

    @RequestMapping(method = RequestMethod.GET)
    public String main() {
        return &quot;help&quot;;
    }
}
</pre></div>


<p>Here&#8217;s the test file:-</p>


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

    private MockMvc mockMvc;

    @Before
    public void setup() {
        mockMvc = MockMvcBuilders.standaloneSetup(new HelpController()).build();
    }

    @Test
    public void main() throws Exception {
        mockMvc.perform(get(&quot;/help&quot;))
                .andExpect(status().isOk())
                .andExpect(view().name(&quot;help&quot;));
    }
}
</pre></div>


<p>When executing this test, we get the following error:-</p>


<div class="wp-block-syntaxhighlighter-code "><pre class="brush: plain; title: ; notranslate">
javax.servlet.ServletException: Circular view path &#x5B;help]: would dispatch
back to the current handler URL &#x5B;/help] again. Check your ViewResolver
setup! (Hint: This may be the result of an unspecified view, due to default
view name generation.)
	at org.springframework.web.servlet.view.InternalResourceView.prepareForRendering(InternalResourceView.java:263)
	at org.springframework.web.servlet.view.InternalResourceView.renderMergedOutputModel(InternalResourceView.java:186)
	at org.springframework.web.servlet.view.AbstractView.render(AbstractView.java:266)
</pre></div>


<h2 class="wp-block-heading">SOLUTION</h2>



<p>The reason this is happening is because the uri &#8220;/help&#8221; matches the returned view name &#8220;help&#8221; and we didn&#8217;t set a <code>ViewResolver</code> when constructing the standalone <code>MockMvc</code>. Since <code>MockMvcBuilders.standaloneSetup(...)</code> doesn&#8217;t load Spring configuration, the Spring MVC configuration under <code>WEB-INF/spring-servlet.xml</code> will not get loaded too.</p>



<p>A typical <code>WEB-INF/spring-servlet.xml</code> looks something like this:-</p>


<div class="wp-block-syntaxhighlighter-code "><pre class="brush: xml; title: ; notranslate">
&lt;?xml version=&quot;1.0&quot; encoding=&quot;UTF-8&quot;?&gt;
&lt;beans ...&gt;

    &lt;context:component-scan base-package=&quot;edu.mayo.requestportal.controller&quot;/&gt;

    &lt;mvc:annotation-driven/&gt;

    &lt;mvc:resources location=&quot;/resources/&quot; mapping=&quot;/resources/**&quot;/&gt;

    &lt;bean id=&quot;viewResolver&quot; class=&quot;org.springframework.web.servlet.view.InternalResourceViewResolver&quot;&gt;
        &lt;property name=&quot;prefix&quot; value=&quot;/WEB-INF/jsp/view/&quot;/&gt;
        &lt;property name=&quot;suffix&quot; value=&quot;.jsp&quot;/&gt;
    &lt;/bean&gt;

    &lt;bean id=&quot;messageSource&quot; class=&quot;org.springframework.context.support.ResourceBundleMessageSource&quot;&gt;
        &lt;property name=&quot;basename&quot; value=&quot;messages&quot;/&gt;
    &lt;/bean&gt;
&lt;/beans&gt;
</pre></div>


<p>To fix this, we need to defined a <code>ViewResolver</code> that mimics the configuration defined under <code>WEB-INF/spring-servlet.xml</code> in the test file:-</p>


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

    private MockMvc mockMvc;

    @Before
    public void setup() {
        InternalResourceViewResolver viewResolver = new InternalResourceViewResolver();
        viewResolver.setPrefix(&quot;/WEB-INF/jsp/view/&quot;);
        viewResolver.setSuffix(&quot;.jsp&quot;);

        mockMvc = MockMvcBuilders.standaloneSetup(new HelpController())
                                 .setViewResolvers(viewResolver)
                                 .build();
    }

    @Test
    public void main() throws Exception {
        mockMvc.perform(get(&quot;/help&quot;))
                .andExpect(status().isOk())
                .andExpect(view().name(&quot;help&quot;));
    }
}
</pre></div><p>The post <a rel="nofollow" href="https://myshittycode.com/2014/01/17/mockmvc-circular-view-path-view-would-dispatch-back-to-the-current-handler-url-view-again/">MockMvc : Circular view path [view]: would dispatch back to the current handler URL [/view] again</a> appeared first on <a rel="nofollow" href="https://myshittycode.com">My Shitty Code</a>.</p>
]]></content:encoded>
					
					<wfw:commentRss>https://myshittycode.com/2014/01/17/mockmvc-circular-view-path-view-would-dispatch-back-to-the-current-handler-url-view-again/feed/</wfw:commentRss>
			<slash:comments>4</slash:comments>
		
		
		<post-id xmlns="com-wordpress:feed-additions:1">332</post-id>	</item>
		<item>
		<title>MockMvc + Mockito = Epic Tests</title>
		<link>https://myshittycode.com/2014/01/16/mockmvc-mockito-epic-tests/</link>
					<comments>https://myshittycode.com/2014/01/16/mockmvc-mockito-epic-tests/#comments</comments>
		
		<dc:creator><![CDATA[Shitty Author]]></dc:creator>
		<pubDate>Fri, 17 Jan 2014 00:37:22 +0000</pubDate>
				<category><![CDATA[Programming Language]]></category>
		<category><![CDATA[Mockito]]></category>
		<category><![CDATA[Spring MVC Test Framework]]></category>
		<category><![CDATA[Unit Testing]]></category>
		<guid isPermaLink="false">http://myshittycode.com/?p=324</guid>

					<description><![CDATA[<p>Spring Framework 3.2 introduces a very elegant way to test Spring MVC controller using MockMvc. Based on the documentation, there are two ways to configure MockMvc:- The first approach will automatically load the Spring configuration and inject WebApplicationContext into the test. The second approach does not load the Spring configuration. While both options work, my [&#8230;]</p>
<p>The post <a rel="nofollow" href="https://myshittycode.com/2014/01/16/mockmvc-mockito-epic-tests/">MockMvc + Mockito = Epic Tests</a> appeared first on <a rel="nofollow" href="https://myshittycode.com">My Shitty Code</a>.</p>
]]></description>
										<content:encoded><![CDATA[
<p><a href="http://docs.spring.io/spring/docs/3.2.x/spring-framework-reference/html/testing.html#spring-mvc-test-framework" target="_blank" rel="noopener">Spring Framework 3.2</a> introduces a very elegant way to test Spring MVC controller using <code>MockMvc</code>.</p>



<p>Based on the documentation, there are two ways to configure <code>MockMvc</code>:-</p>



<ul class="wp-block-list">
<li><code>MockMvcBuilders.webAppContextSetup(webApplicationContext).build()</code></li>



<li><code>MockMvcBuilders.standaloneSetup(controller).build()</code></li>
</ul>



<p>The first approach will automatically load the Spring configuration and inject <code>WebApplicationContext</code> into the test. The second approach does not load the Spring configuration.</p>



<p>While both options work, my preference is to use the second approach that doesn&#8217;t load the Spring configuration. Rather, I use Mockito to mock out all the dependencies within the controller.</p>



<h2 class="wp-block-heading">EXAMPLE</h2>



<p>Let&#8217;s assume we want to test this controller:-</p>


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

    @Autowired
    private RequestService requestService;

    @Autowired
    private CommentValidator validator;

    @InitBinder(&quot;commentForm&quot;)
    protected void initBinder(WebDataBinder binder) {
        binder.setValidator(validator);
    }

    @RequestMapping(method = RequestMethod.POST)
    public String saveComment(@PathVariable String uuid,
                              @Valid @ModelAttribute CommentForm commentForm,
                              BindingResult result,
                              Model model) {

        RequestComment requestComment = requestService.getRequestCommentByUUID(uuid);

        if (requestComment == null) {
            return &quot;redirect:/dashboard&quot;;
        }

        if (result.hasErrors()) {
            return &quot;comment&quot;;
        }

        return &quot;ok&quot;;
    }
}
</pre></div>


<h2 class="wp-block-heading">SETTING UP TEST FILE</h2>



<p>To test <code>/comment/{uuid} POST</code>, we need three tests:-</p>



<ul class="wp-block-list">
<li><code>requestComment</code> is null, which returns <code>redirect:/dashboard</code> view.</li>



<li>Form validation contains error, which returns <code>comment</code> view.</li>



<li>Everything works fine, which returns <code>ok</code> view.</li>
</ul>



<p>The test file looks something like this:-</p>


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

    @Mock
    private RequestService requestService;

    @Mock
    private CommentValidator validator;

    @InjectMocks
    private CommentController commentController;

    private MockMvc mockMvc;

    @Before
    public void setup() {
        MockitoAnnotations.initMocks(this);

        mockMvc = MockMvcBuilders.standaloneSetup(commentController).build();

        when(validator.supports(any(Class.class))).thenReturn(true);
    }

    @Test
    public void testSaveComment_RequestCommentNotFound() throws Exception {
		...
    }

    @Test
    public void testSaveComment_FormError() throws Exception {
		...
    }

    @Test
    public void testSaveComment_NoError() throws Exception {
		...
    }
}
</pre></div>


<p>Because the controller has two dependencies ( <code>RequestService</code> and <code>CommentValidator</code> ) injected into it through Spring autowiring, we are going to create these two mocks and inject them into the controller by annotating them with Mockito&#8217;s <code>@Mock</code> and <code>@InjectMocks</code> accordingly.</p>



<p>In <code>setup(...)</code> method, the first line initializes objects annotated with <code>@Mock</code>. The second line initializes <code>MockMvc</code> without loading Spring configuration because we want the flexibility to mock the dependencies out using Mockito. The third line instructs the validator to return <code>true</code> when <code>validator.support(...)</code> is invoked. If the third line is left out, you will get this exception when <code>binder.setValidator(validator)</code> in the <code>controller.initBinder(...)</code> is invoked:-</p>


<div class="wp-block-syntaxhighlighter-code "><pre class="brush: plain; title: ; notranslate">
org.springframework.web.util.NestedServletException: Request processing failed;
nested exception is java.lang.IllegalStateException: Invalid target for Validator
&#x5B;validator]: com.choonchernlim.epicapp.form.CommentForm@1a80b973
</pre></div>


<p>Finally, we have three stubs to test the conditions defined earlier.</p>



<h2 class="wp-block-heading">TEST CASE 1: <code>requestComment</code> is null</h2>


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

	...

    @Test
    public void testSaveComment_RequestCommentNotFound() throws Exception {
        when(requestService.getRequestCommentByUUID(&quot;123&quot;)).thenReturn(null);

        mockMvc.perform(post(&quot;/comment/{uuid}&quot;, &quot;123&quot;))
                .andExpect(status().isMovedTemporarily())
                .andExpect(view().name(&quot;redirect:/dashboard&quot;));
    }
}
</pre></div>


<p>The first test is rather easy. All we need to do is to instruct <code>requestService.getRequestCommentByUUID(...)</code> to return null when it is invoked.</p>



<h2 class="wp-block-heading">TEST CASE 2: Form validation contains error</h2>


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

	...

    @Test
    public void testSaveComment_FormError() throws Exception {
        when(requestService.getRequestCommentByUUID(&quot;123&quot;)).thenReturn(new RequestComment());

        doAnswer(new Answer() {
            @Override
            public Object answer(InvocationOnMock invocationOnMock) throws Throwable {
                Errors errors = (Errors) invocationOnMock.getArguments()&#x5B;1];
                errors.reject(&quot;forcing some error&quot;);
                return null;
            }
        }).when(validator).validate(anyObject(), any(Errors.class));

        mockMvc.perform(post(&quot;/comment/{uuid}&quot;, &quot;123&quot;))
                .andExpect(status().isOk())
                .andExpect(view().name(&quot;comment&quot;));
    }
}
</pre></div>


<p>The second test is a little complicated. We need to instruct <code>requestService.getRequestCommentByUUID(...)</code> to return a <code>RequestComment</code> object. Then, we use Mockito&#8217;s <code>doAnswer(...)</code> to set a dummy error value to <code>Errors</code> object, which is the second argument of <code>validator.validate(...)</code>. Setting this value will cause <code>result.hasErrors()</code> to evaluate to <code>true</code>.</p>



<h2 class="wp-block-heading">TEST CASE 3: Everything works fine</h2>


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

	...

    @Test
    public void testSaveComment_NoError() throws Exception {
        when(requestService.getRequestCommentByUUID(&quot;123&quot;)).thenReturn(new RequestComment());

        mockMvc.perform(post(&quot;/comment/{uuid}&quot;, &quot;123&quot;))
                .andExpect(status().isOk())
                .andExpect(view().name(&quot;ok&quot;));
    }
}
</pre></div>


<p>The third test is rather easy too. We need to instruct <code>requestService.getRequestCommentByUUID(...)</code> to return a <code>RequestComment</code> object&#8230; and that&#8217;s it.</p>



<h2 class="wp-block-heading">CONCLUSION</h2>



<p>See&#8230; it&#8217;s not really that hard. The combination of Mockito and Spring Test Framework 3.2 provides us a great flexibility to test our Spring MVC controllers. Granted, we should already have our unit tests for the two dependencies ( <code>RequestService</code> and <code>CommentValidator</code> ) already. So, it is safe to alter the behavior of these dependencies using Mockito to test every possible path in the controller.</p>
<p>The post <a rel="nofollow" href="https://myshittycode.com/2014/01/16/mockmvc-mockito-epic-tests/">MockMvc + Mockito = Epic Tests</a> appeared first on <a rel="nofollow" href="https://myshittycode.com">My Shitty Code</a>.</p>
]]></content:encoded>
					
					<wfw:commentRss>https://myshittycode.com/2014/01/16/mockmvc-mockito-epic-tests/feed/</wfw:commentRss>
			<slash:comments>2</slash:comments>
		
		
		<post-id xmlns="com-wordpress:feed-additions:1">324</post-id>	</item>
		<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 56/67 queries in 0.016 seconds using Disk

Served from: myshittycode.com @ 2026-02-18 14:42:22 by W3 Total Cache
-->