-
Notifications
You must be signed in to change notification settings - Fork 0
/
mockmvc.html
18 lines (17 loc) · 19.6 KB
/
mockmvc.html
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
<!DOCTYPE html><html lang="de-ch"><head><meta charset="utf-8"><meta http-equiv="X-UA-Compatible" content="IE=edge"><meta name="viewport" content="width=device-width,initial-scale=1"><title>Testing with MockMVC - Finecloud</title><meta name="description" content="Why use Spring MockMVC? Spring MockMVC allows you to test the controller interactions in a servlet context without the application running in an application server. Mockito is the most popular mocking framework for testing Java Mocks (aka Test Doubles) are alternate implementations of objects to…"><meta name="generator" content="Publii Open-Source CMS for Static Site"><link rel="stylesheet" href="https://www.finecloud.ch/media/plugins/syntaxHighlighter/prism-black.css"><link rel="canonical" href="https://www.finecloud.ch/mockmvc.html"><link rel="alternate" type="application/atom+xml" href="https://www.finecloud.ch/feed.xml"><link rel="alternate" type="application/json" href="https://www.finecloud.ch/feed.json"><meta property="og:title" content="Testing with MockMVC"><meta property="og:site_name" content="Finecloud"><meta property="og:description" content="Why use Spring MockMVC? Spring MockMVC allows you to test the controller interactions in a servlet context without the application running in an application server. Mockito is the most popular mocking framework for testing Java Mocks (aka Test Doubles) are alternate implementations of objects to…"><meta property="og:url" content="https://www.finecloud.ch/mockmvc.html"><meta property="og:type" content="article"><link rel="shortcut icon" href="https://www.finecloud.ch/media/website/finecloud.png" type="image/png"><link rel="stylesheet" href="https://www.finecloud.ch/assets/css/style.css?v=39da73365516a098a9b73b721fc970e2"><script type="application/ld+json">{"@context":"http://schema.org","@type":"Article","mainEntityOfPage":{"@type":"WebPage","@id":"https://www.finecloud.ch/mockmvc.html"},"headline":"Testing with MockMVC","datePublished":"2023-04-06T15:31","dateModified":"2023-04-06T21:22","description":"Why use Spring MockMVC? Spring MockMVC allows you to test the controller interactions in a servlet context without the application running in an application server. Mockito is the most popular mocking framework for testing Java Mocks (aka Test Doubles) are alternate implementations of objects to…","author":{"@type":"Person","name":"Finecloud","url":"https://www.finecloud.ch/authors/finecloud/"},"publisher":{"@type":"Organization","name":"Finecloud"}}</script><meta name="google-site-verification" content="seFY9U12uiEq5U3_MyZiX6XWzk0AVFl9zITr2ZKsytY"></head><body><div class="site-container"><header class="top" id="js-header"><a class="logo" href="https://www.finecloud.ch/">Finecloud</a><nav class="navbar js-navbar"><button class="navbar__toggle js-toggle" aria-label="Menu" aria-haspopup="true" aria-expanded="false"><span class="navbar__toggle-box"><span class="navbar__toggle-inner">Menu</span></span></button><ul class="navbar__menu"><li><a href="https://www.finecloud.ch/" target="_self">Blog</a></li><li><a href="https://www.finecloud.ch/tags/" target="_self">Tags</a></li></ul></nav><div class="search"><div class="search__overlay js-search-overlay"><div class="search__overlay-inner"><form action="https://www.finecloud.ch/search.html" class="search__form"><input class="search__input js-search-input" type="search" name="q" placeholder="search..." aria-label="search..." autofocus="autofocus"></form><button class="search__close js-search-close" aria-label="Close">Close</button></div></div><button class="search__btn js-search-btn" aria-label="Search"><svg role="presentation" focusable="false"><use xlink:href="https://www.finecloud.ch/assets/svg/svg-map.svg#search"/></svg></button></div></header><main><article class="post"><div class="hero"><figure class="hero__image hero__image--overlay"><img src="https://www.finecloud.ch/media/website/download.jpg" srcset="https://www.finecloud.ch/media/website/responsive/download-xs.jpg 300w, https://www.finecloud.ch/media/website/responsive/download-sm.jpg 480w, https://www.finecloud.ch/media/website/responsive/download-md.jpg 768w, https://www.finecloud.ch/media/website/responsive/download-lg.jpg 1024w, https://www.finecloud.ch/media/website/responsive/download-xl.jpg 1360w, https://www.finecloud.ch/media/website/responsive/download-2xl.jpg 1600w" sizes="100vw" loading="eager" alt=""></figure><header class="hero__content"><div class="wrapper"><div class="post__meta"><time datetime="2023-04-06T15:31">April 6, 2023</time></div><h1>Testing with MockMVC</h1></div></header></div><div class="wrapper post__entry"><div class="post__toc"><h3>Table of Contents</h3><ul><li><a href="#mcetoc_1gtc0a48v1bq">Why use Spring MockMVC?</a></li><li><a href="#mcetoc_1gtbugt571b8">Types of Tests</a><ul><li><a href="#mcetoc_1gtbugt571b9">Unit Tests / Unit Testing</a></li></ul></li><li><a href="#mcetoc_1gtbugt571ba">Integration Tests</a></li><li><a href="#mcetoc_1gtbugt571bb">Functional Tests</a></li><li><a href="#mcetoc_1gtbugt571bc">The major challenge with testing Servlets and Controllers</a></li><li><a href="#mcetoc_1gtbugt571bd">Spring Boot Test Splices</a></li><li><a href="#mcetoc_1gtbugt571be">Using Mocks</a></li><li><a href="#mcetoc_1gtbugt571bf">What is Mockito?</a></li><li><a href="#mcetoc_1gtbugt571bg">Types of Mocks</a></li><li><a href="#mcetoc_1gtbugt571bh">Testing Controllers</a></li></ul></div><div class="question--question--152Yi"><div class="ud-text-bold question--title--2FD-U"><div class="question--title-text--2kBEO rt-scaffolding" data-purpose="safely-set-inner-html:rich-text-viewer:html"><h3 id="mcetoc_1gtc0a48v1bq">Why use Spring MockMVC?</h3></div></div><div class="question--answer--2ASXa"><div data-purpose="safely-set-inner-html:submission:user-answer-body"><p>Spring MockMVC allows you to test the controller interactions in a servlet context without the application running in an application server.</p></div></div></div><h3 id="mcetoc_1gtbugt571b8">Types of Tests</h3><div class="page" title="Page 2"><div class="section"><div class="layoutArea"><div class="column"><h4 id="mcetoc_1gtbugt571b9">Unit Tests / Unit Testing</h4><ul><li>Code written to test code under test</li><li><span style="color: var(--text-primary-color); font-family: var(--editor-font-family); font-size: inherit; font-weight: var(--font-weight-normal);">Designed to test specific sections of code</span></li><li><span style="color: var(--text-primary-color); font-family: var(--editor-font-family); font-size: inherit; font-weight: var(--font-weight-normal);">Percentage of lines of code tested is code coverage</span></li><li><span style="color: var(--text-primary-color); font-family: var(--editor-font-family); font-size: inherit; font-weight: var(--font-weight-normal);">Ideal coverage is in the 70-80% range</span></li><li><span style="color: var(--text-primary-color); font-family: var(--editor-font-family); font-size: inherit; font-weight: var(--font-weight-normal);">Should be ‘unity’ and execute very fast</span></li><li><span style="color: var(--text-primary-color); font-family: var(--editor-font-family); font-size: inherit; font-weight: var(--font-weight-normal);">Should have no external dependencies</span></li><li><span style="color: var(--text-primary-color); font-family: var(--editor-font-family); font-size: inherit; font-weight: var(--font-weight-normal);">ie no database, no Spring context, etc</span></li></ul><div class="page" title="Page 3"><div class="section"><div class="layoutArea"><div class="column"><h3 id="mcetoc_1gtbugt571ba">Integration Tests</h3><ul><li>Designed to test behaviors between objects and parts of the overall system</li><li><span style="color: var(--text-primary-color); font-family: var(--editor-font-family); font-size: inherit; font-weight: var(--font-weight-normal);">Much larger scope</span></li><li><span style="color: var(--text-primary-color); font-family: var(--editor-font-family); font-size: inherit; font-weight: var(--font-weight-normal);">Can include the Spring Context, database, and message brokers</span></li><li><span style="color: var(--text-primary-color); font-family: var(--editor-font-family); font-size: inherit; font-weight: var(--font-weight-normal);">Will run much slower than unit tests</span></li></ul><h3 id="mcetoc_1gtbugt571bb">Functional Tests</h3><ul><li><span style="color: var(--text-primary-color); font-family: var(--editor-font-family); font-size: inherit; font-weight: var(--font-weight-normal);">Typically means you are testing the running application</span></li><li><span style="color: var(--text-primary-color); font-family: var(--editor-font-family); font-size: inherit; font-weight: var(--font-weight-normal);">Application is live, likely deployed in a known environment</span></li><li><span style="color: var(--text-primary-color); font-family: var(--editor-font-family); font-size: inherit; font-weight: var(--font-weight-normal);">Functional touch points are tested - (i.e. Using a web driver, calling web services, sending / receiving messages, etc)</span></li></ul><h3 id="mcetoc_1gtbugt571bc">The major challenge with testing Servlets and Controllers</h3><div class="page" title="Page 5"><div class="section"><div class="layoutArea"><div class="column"><ul><li>Spring MVC Controllers are tricky to test property</li><li>Controllers have a high degree of integration with the Spring MVC Framework</li><li>Request path and HTTP Method decides which method to invoke</li><li>Path variables are parsed from path</li><li>JSON is bound to POJOs</li><li>Response is expressed as a HTTP Response</li><li>JUnit tests are NOT sufficient to test the framework interaction</li><li><span style="color: var(--text-primary-color); font-family: var(--editor-font-family); font-size: inherit; font-weight: var(--font-weight-normal);">Spring Mock MVC is a testing environment for the testing of Spring MVC controllers</span><ul><li><span style="color: var(--text-primary-color); font-family: var(--editor-font-family); font-size: inherit; font-weight: var(--font-weight-normal);">Provides mocks of the Servlet runtime environment</span><br><ul><li><span style="color: var(--text-primary-color); font-family: var(--editor-font-family); font-size: inherit; font-weight: var(--font-weight-normal);">HTTP Request / Response, Dispatcher Servlet, etc</span></li><li><span style="color: var(--text-primary-color); font-family: var(--editor-font-family); font-size: inherit; font-weight: var(--font-weight-normal);">Simulates the execution of controller as if it was running under Spring within Tomcat</span></li></ul></li></ul></li><li><span style="color: var(--text-primary-color); font-family: var(--editor-font-family); font-size: inherit; font-weight: var(--font-weight-normal);">Can be run with or without the Spring Context</span></li><li><span style="color: var(--text-primary-color); font-family: var(--editor-font-family); font-size: inherit; font-weight: var(--font-weight-normal);">True unit test when run without the Spring Context</span></li><li><span style="color: var(--text-primary-color); font-family: var(--editor-font-family); font-size: inherit; font-weight: var(--font-weight-normal);">Technically an Integration Test when used in conjunction with Spring Context</span></li></ul><div class="page" title="Page 7"><div class="section"><div class="layoutArea"><div class="column"><h3 id="mcetoc_1gtbugt571bd">Spring Boot Test Splices</h3><div class="page" title="Page 7"><div class="section"><div class="layoutArea"><div class="column"><ul><li>Spring Boot supports a concept of what is called Test Splices</li><li>Test Splices bring up a targeted segment of the Auto-Configured Spring Boot Environment<ul><li><span style="color: var(--text-primary-color); font-family: var(--editor-font-family); font-size: inherit; font-weight: var(--font-weight-normal);">ie - Just the Database components; or just the web components</span></li><li><span style="color: var(--text-primary-color); font-family: var(--editor-font-family); font-size: inherit; font-weight: var(--font-weight-normal);">User defined Spring beans typically are NOT initialized</span></li></ul></li><li><span style="color: var(--text-primary-color); font-family: var(--editor-font-family); font-size: inherit; font-weight: var(--font-weight-normal);">@WebMvcTest - is a Spring Boot test splice which creates a MockMVC environment for </span><span style="color: var(--text-primary-color); font-family: var(--editor-font-family); font-size: inherit; font-weight: var(--font-weight-normal);">the controller (or controllers) under test</span><br><ul><li><span style="color: var(--text-primary-color); font-family: var(--editor-font-family); font-size: inherit; font-weight: var(--font-weight-normal);">Dependencies of controllers are NOT included</span></li></ul></li></ul><h3 id="mcetoc_1gtbugt571be">Using Mocks</h3><div class="page" title="Page 8"><div class="section"><div class="layoutArea"><div class="column"><ul><li>Controller dependencies must be added to the Spring Context in the test environment</li><li>Dependencies can be any proper implementation<ul><li><span style="color: var(--text-primary-color); font-family: var(--editor-font-family); font-size: inherit; font-weight: var(--font-weight-normal);">Example of why we code to an interface, any implementation will work</span></li><li><span style="color: var(--text-primary-color); font-family: var(--editor-font-family); font-size: inherit; font-weight: var(--font-weight-normal);">We could easily use the hash map implementation we’ve been using in the course</span></li></ul></li><li><span style="color: var(--text-primary-color); font-family: var(--editor-font-family); font-size: inherit; font-weight: var(--font-weight-normal);">For testing, it is common to use mock objects</span></li><li><span style="color: var(--text-primary-color); font-family: var(--editor-font-family); font-size: inherit; font-weight: var(--font-weight-normal);">Mocks allow you to supply a specific response for a given input</span><ul><li>ie - when method abcd is called, return foo...</li></ul></li></ul></div></div></div></div><p> </p><h3 id="mcetoc_1gtbugt571bf">What is Mockito?</h3><div class="page" title="Page 9"><div class="section"><div class="layoutArea"><div class="column"><ul><li><p>Mockito is the most popular mocking framework for testing Java</p></li><li>Mocks (aka Test Doubles) are alternate implementations of objects to replace real objects in tests</li><li>Works well with Dependency Injection</li><li>For the class under test, injected dependencies can be mocks</li></ul></div></div></div></div><h3 id="mcetoc_1gtbugt571bg">Types of Mocks</h3><ul><li><span style="color: var(--text-primary-color); font-family: var(--editor-font-family); font-size: inherit; font-weight: var(--font-weight-normal);">Dummy - Object used just to get the code to compile</span></li><li><span style="color: var(--text-primary-color); font-family: var(--editor-font-family); font-size: inherit; font-weight: var(--font-weight-normal);">Fake - An object that has an implementation, but not production ready</span></li><li><span style="color: var(--text-primary-color); font-family: var(--editor-font-family); font-size: inherit; font-weight: var(--font-weight-normal);">Stub - An object with pre-defined answers to method calls</span></li><li><span style="color: var(--text-primary-color); font-family: var(--editor-font-family); font-size: inherit; font-weight: var(--font-weight-normal);">Mock - An object with pre-defined answers to method calls, and has expectations of executions. Can throw an exception if an unexpected invocation is detected</span></li><li><span style="color: var(--text-primary-color); font-family: var(--editor-font-family); font-size: inherit; font-weight: var(--font-weight-normal);">Spy - In Mockito Spies are Mock like wrappers around the actual object</span></li></ul><h3 id="mcetoc_1gtbugt571bh">Testing Controllers</h3><div class="page" title="Page 12"><div class="section"><div class="layoutArea"><div class="column"><ul><li>Argument captors can be used to verify request data is properly being parsed and passed to service layer</li><li>Verify interactions can be used Mocked object was called</li><li>Mock return values supply data back to controller<ul><li>ie - object returned when getById is called on service</li></ul></li><li>Mocks can also be instructed to throw exceptions to test exception handling</li></ul></div></div></div></div></div></div></div></div></div></div></div></div></div></div></div></div></div></div></div></div></div></div></div></div></div><footer class="wrapper post__footer"><p class="post__last-updated">This article was updated on April 6, 2023</p><ul class="post__tag"><li><a href="https://www.finecloud.ch/tags/java/">java</a></li><li><a href="https://www.finecloud.ch/tags/softwareentwicklung/">software development</a></li><li><a href="https://www.finecloud.ch/tags/spring/">spring</a></li><li><a href="https://www.finecloud.ch/tags/spring-framework/">spring-framework</a></li></ul><div class="post__share"></div></footer></article><nav class="post__nav"><div class="post__nav-inner"><div class="post__nav-prev"><svg width="1.041em" height="0.416em" aria-hidden="true"><use xlink:href="https://www.finecloud.ch/assets/svg/svg-map.svg#arrow-prev"/></svg> <a href="https://www.finecloud.ch/project-lombok.html" class="post__nav-link" rel="prev"><span>Previous</span> Project Lombok</a></div><div class="post__nav-next"><a href="https://www.finecloud.ch/spring-exception-handling.html" class="post__nav-link" rel="next"><span>Next</span> Spring Exception Handling </a><svg width="1.041em" height="0.416em" aria-hidden="true"><use xlink:href="https://www.finecloud.ch/assets/svg/svg-map.svg#arrow-next"/></svg></div></div></nav><div class="post__related related"><div class="wrapper"><h2 class="h5 related__title">You should also read:</h2><article class="related__item"><div class="feed__meta"><time datetime="2023-12-10T13:52" class="feed__date">Dezember 10, 2023</time></div><h3 class="h1"><a href="https://www.finecloud.ch/working-efficient-within-different-directories-in-a-linux-shell.html">Working efficient within different directories in a Linux Shell</a></h3></article><article class="related__item"><div class="feed__meta"><time datetime="2022-09-23T07:41" class="feed__date">September 23, 2022</time></div><h3 class="h1"><a href="https://www.finecloud.ch/getting-stared-with-spring-framework.html">Getting stared with the Spring Framework</a></h3></article><article class="related__item"><div class="feed__meta"><time datetime="2022-09-06T14:20" class="feed__date">September 6, 2022</time></div><h3 class="h1"><a href="https://www.finecloud.ch/java-working-with-a-database.html">Java working with databases</a></h3></article></div></div></main><footer class="footer"><div class="footer__copyright"><p>Powered by Publii</p></div><button onclick="backToTopFunction()" id="backToTop" class="footer__bttop" aria-label="Back to top" title="Back to top"><svg><use xlink:href="https://www.finecloud.ch/assets/svg/svg-map.svg#toparrow"/></svg></button></footer></div><script>window.publiiThemeMenuConfig = {
mobileMenuMode: 'sidebar',
animationSpeed: 300,
submenuWidth: 'auto',
doubleClickTime: 500,
mobileMenuExpandableSubmenus: true,
relatedContainerForOverlayMenuSelector: '.top',
};</script><script defer="defer" src="https://www.finecloud.ch/assets/js/scripts.min.js?v=6ca8b60e6534a3888de1205e82df8528"></script><script>var images = document.querySelectorAll('img[loading]');
for (var i = 0; i < images.length; i++) {
if (images[i].complete) {
images[i].classList.add('is-loaded');
} else {
images[i].addEventListener('load', function () {
this.classList.add('is-loaded');
}, false);
}
}</script><script defer="defer" src="https://www.finecloud.ch/media/plugins/syntaxHighlighter/prism.js"></script></body></html>