{"id":50846,"date":"2016-01-08T13:00:39","date_gmt":"2016-01-08T11:00:39","guid":{"rendered":"http:\/\/www.javacodegeeks.com\/?p=50846"},"modified":"2016-01-07T20:22:36","modified_gmt":"2016-01-07T18:22:36","slug":"mock-spring-bean-version-2","status":"publish","type":"post","link":"https:\/\/www.javacodegeeks.com\/2016\/01\/mock-spring-bean-version-2.html","title":{"rendered":"How to mock Spring bean (version 2)"},"content":{"rendered":"<p>About a year ago, I wrote a <a href=\"http:\/\/www.javacodegeeks.com\/2014\/12\/how-to-mock-spring-bean-without-springockito.html\">blog post how to mock Spring Bean<\/a>. Patterns described there were little bit invasive to the production code.\u00a0 As one of the readers <a href=\"http:\/\/lkrnac.net\/blog\/2014\/12\/mock-spring-bean\/#comment-75376\">Colin correctly pointed out in comment<\/a>, there is better alternative to spy\/mock Spring bean based on <strong><code>@Profile<\/code><\/strong> annotation. This blog post is going to describe this technique. I used this approach with success at work and also in my side projects.<\/p>\n<p><strong>Note that widespread mocking in your application is often considered as design smell.<\/strong><\/p>\n<h2>Introducing production code<\/h2>\n<p>First of all we need code under test to demonstrate mocking. We will use these simple classes:<\/p>\n<pre class=\" brush:java\">@Repository\r\npublic class AddressDao {\r\n\tpublic String readAddress(String userName) {\r\n\t\treturn \"3 Dark Corner\";\r\n\t}\r\n}\r\n\r\n@Service\r\npublic class AddressService {\r\n\tprivate AddressDao addressDao;\r\n\t\r\n\t@Autowired\r\n\tpublic AddressService(AddressDao addressDao) {\r\n\t\tthis.addressDao = addressDao;\r\n\t}\r\n\t\r\n\tpublic String getAddressForUser(String userName){\r\n\t\treturn addressDao.readAddress(userName);\r\n\t}\r\n}\r\n\r\n@Service\r\npublic class UserService {\r\n\tprivate AddressService addressService;\r\n\r\n\t@Autowired\r\n\tpublic UserService(AddressService addressService) {\r\n\t\tthis.addressService = addressService;\r\n\t}\r\n\t\r\n\tpublic String getUserDetails(String userName){\r\n\t\tString address = addressService.getAddressForUser(userName);\r\n\t\treturn String.format(\"User %s, %s\", userName, address);\r\n\t}\r\n}<\/pre>\n<p>Of course this code doesn\u2019t make much sense, but will be good to demonstrate how to mock Spring bean. <strong><code>AddressDao<\/code><\/strong> just returns string and thus simulates read from some data source. It is autowired into <strong><code>AddressService<\/code><\/strong>. This bean is autowired into <strong><code>UserService<\/code><\/strong>, which is used to construct string with user name and address.<\/p>\n<p>Notice that we are using <strong>constructor injection<\/strong> as field injection is considered as bad practice. If you want to enforce constructor injection for your application, Oliver Gierke (Spring ecosystem developer and Spring Data lead) recently created very nice project <a href=\"https:\/\/github.com\/olivergierke\/ninjector\">Ninjector<\/a>.<\/p>\n<p>Configuration which scans all these beans is pretty standard Spring Boot main class:<\/p>\n<pre class=\" brush:java\">@SpringBootApplication\r\npublic class SimpleApplication {\r\n\u00a0\u00a0 \u00a0public static void main(String[] args) {\r\n\u00a0\u00a0 \u00a0\u00a0\u00a0 \u00a0SpringApplication.run(SimpleApplication.class, args);\r\n\u00a0\u00a0 \u00a0}\r\n}<\/pre>\n<h2>Mock Spring bean (without AOP)<\/h2>\n<p>Let\u2019s test the <code><strong>AddressService<\/strong><\/code> class where we mock <strong><code>AddressDao<\/code><\/strong>. We can create this mock via Spring\u2019 <strong><code>@Profiles<\/code><\/strong> and <strong>@Primary<\/strong> annotations this way:<\/p>\n<pre class=\" brush:java\">@Profile(\"AddressService-test\")\r\n@Configuration\r\npublic class AddressDaoTestConfiguration {\r\n\t@Bean\r\n\t@Primary\r\n\tpublic AddressDao addressDao() {\r\n\t\treturn Mockito.mock(AddressDao.class);\r\n\t}\r\n}<\/pre>\n<p>This test configuration will be applied only when Spring profile <code><strong>AddressService-test<\/strong><\/code> is active. When it\u2019s applied, it registers bean of type <strong><code>AddressDao<\/code><\/strong>, which is mock instance created by <strong>Mockito<\/strong>. <strong><code>@Primary<\/code><\/strong> annotation tells Spring to use this instance instead of real one when somebody autowire <code><strong>AddressDao<\/strong><\/code> bean.<\/p>\n<p>Test class is using <strong>JUnit<\/strong> framework:<\/p>\n<pre class=\" brush:java\">@ActiveProfiles(\"AddressService-test\")\r\n@RunWith(SpringJUnit4ClassRunner.class)\r\n@SpringApplicationConfiguration(SimpleApplication.class)\r\npublic class AddressServiceITest {\r\n\t@Autowired \r\n\tprivate AddressService addressService;\r\n\r\n\t@Autowired\r\n\tprivate AddressDao addressDao;\r\n\r\n\t@Test\r\n\tpublic void testGetAddressForUser() {\r\n\t\t\/\/ GIVEN\r\n\t\tMockito.when(addressDao.readAddress(\"john\"))\r\n\t\t\t.thenReturn(\"5 Bright Corner\");\r\n\r\n\t\t\/\/ WHEN \r\n\t\tString actualAddress = addressService.getAddressForUser(\"john\");\r\n  \r\n\t\t\/\/ THEN   \r\n\t\tAssert.assertEquals(\"5 Bright Corner\", actualAddress);\r\n\t}\r\n}<\/pre>\n<p>We activate profile <strong><code>AddressService-test<\/code><\/strong> to enable <strong><code>AddressDao<\/code><\/strong> mocking. Annotation <strong><code>@RunWith<\/code><\/strong> is needed for Spring integration tests and <strong><code>@SpringApplicationConfiguration<\/code><\/strong> defines which Spring configuration will be used to construct context for testing. Before the test, we autowire instance of <strong><code>AddressService<\/code><\/strong> under test and <strong><code>AddressDao<\/code><\/strong> mock.<\/p>\n<p>Subsequent testing method should be clear if you are using Mockito. In <strong><code>GIVEN<\/code><\/strong> phase, we record desired behavior into mock instance. In <strong><code>WHEN<\/code><\/strong> phase, we execute testing code and in <strong><code>THEN<\/code><\/strong> phase, we verify if testing code returned value we expect.<\/p>\n<h2>Spy on Spring Bean (without AOP)<\/h2>\n<p>For spying example, will be spying on <strong><code>AddressService<\/code><\/strong> instance:<\/p>\n<pre class=\" brush:java\">@Profile(\"UserService-test\")\r\n@Configuration\r\npublic class AddressServiceTestConfiguration {\r\n\t@Bean\r\n\t@Primary\r\n\tpublic AddressService addressServiceSpy(AddressService addressService) {\r\n\t\treturn Mockito.spy(addressService);\r\n\t}\r\n}<\/pre>\n<p>This Spring configuration will be component scanned only if profile <strong><code>UserService-test<\/code><\/strong> will be active. It defines primary bean of type <strong><code>AddressService<\/code><\/strong>. <strong><code>@Primary<\/code><\/strong> tells Spring to use this instance in case two beans of this type are present in Spring context.\u00a0 During construction of this bean we autowire existing instance of <strong><code>AddressService<\/code><\/strong> from Spring context and use Mockito\u2019s spying feature. The bean we are registering is effectively delegating all the calls to original instance, but Mockito spying allows us to verify interactions on spied instance.<div style=\"display:inline-block; margin: 15px 0;\"> <div id=\"adngin-JavaCodeGeeks_incontent_video-0\" style=\"display:inline-block;\"><\/div> <\/div><\/p>\n<p>We will test behavior of <strong><code>UserService<\/code><\/strong> this way:<\/p>\n<pre class=\" brush:java\">@ActiveProfiles(\"UserService-test\")\r\n@RunWith(SpringJUnit4ClassRunner.class)\r\n@SpringApplicationConfiguration(SimpleApplication.class)\r\npublic class UserServiceITest {\r\n\t@Autowired\r\n\tprivate UserService userService;\r\n\r\n\t@Autowired\r\n\tprivate AddressService addressService;\r\n \r\n\t@Test\r\n\tpublic void testGetUserDetails() {\r\n\t\t\/\/ GIVEN - Spring scanned by SimpleApplication class\r\n\r\n\t\t\/\/ WHEN\r\n\t\tString actualUserDetails = userService.getUserDetails(\"john\");\r\n \r\n\t\t\/\/ THEN\r\n\t\tAssert.assertEquals(\"User john, 3 Dark Corner\", actualUserDetails);\r\n\t\tMockito.verify(addressService).getAddressForUser(\"john\");\r\n\t}\r\n}<\/pre>\n<p>For testing we activate <strong><code>UserService-test<\/code><\/strong> profile so our spying configuration will be applied. We autowire <strong><code>UserService<\/code><\/strong> which is under test and <strong><code>AddressService<\/code><\/strong>, which is being spied via Mockito.<\/p>\n<p>We don\u2019t need to prepare any behavior for testing in <strong><code>GIVEN<\/code><\/strong> phase. <strong><code>W<\/code><code>HEN<\/code><\/strong> phase is obviously executing code under test. In <code><strong>THEN<\/strong><\/code> phase we verify if testing code returned value we expect and also if <strong><code>addressService<\/code><\/strong> call was executed with correct parameter.<\/p>\n<h2>Problems with Mockito and Spring AOP<\/h2>\n<p>Let say now we want to use Spring AOP module to handle some cross-cutting concerns. For example to log calls on our Spring beans this way:<\/p>\n<pre class=\" brush:java\">package net.lkrnac.blog.testing.mockbeanv2.aoptesting;\r\n\r\nimport org.aspectj.lang.JoinPoint;\r\nimport org.aspectj.lang.annotation.Aspect;\r\nimport org.aspectj.lang.annotation.Before;\r\nimport org.springframework.context.annotation.Profile;\r\nimport org.springframework.stereotype.Component;\r\n\r\nimport lombok.extern.slf4j.Slf4j;\r\n\u00a0\u00a0 \u00a0\r\n@Aspect\r\n@Component\r\n@Slf4j\r\n@Profile(\"aop\") \/\/only for example purposes\r\npublic class AddressLogger {\r\n\u00a0\u00a0 \u00a0@Before(\"execution(* net.lkrnac.blog.testing.mockbeanv2.beans.*.*(..))\")\r\n\u00a0\u00a0 \u00a0public void logAddressCall(JoinPoint jp){\r\n\u00a0\u00a0 \u00a0\u00a0\u00a0 \u00a0log.info(\"Executing method {}\", jp.getSignature());\r\n\u00a0\u00a0 \u00a0}\r\n}<\/pre>\n<p>This AOP Aspect is applied before call on Spring beans from package <strong><code>net.lkrnac.blog.testing.mockbeanv2<\/code><\/strong>. It is using Lombok\u2019s annotation <strong><code>@Slf4j<\/code><\/strong> to log signature of called method. Notice that this bean is created only when <strong><code>aop<\/code><\/strong> profile is defined. We are using this profile to separate AOP and non-AOP testing examples. In a real application you wouldn\u2019t want to use such profile.<\/p>\n<p>We also need to enable AspectJ for our application, therefore all the following examples will be using this Spring Boot main class:<\/p>\n<pre class=\" brush:java\">@SpringBootApplication\r\n@EnableAspectJAutoProxy\r\npublic class AopApplication {\r\n\u00a0\u00a0 \u00a0public static void main(String[] args) {\r\n\u00a0\u00a0 \u00a0\u00a0\u00a0 \u00a0SpringApplication.run(AopApplication.class, args);\r\n\u00a0\u00a0 \u00a0}\r\n}<\/pre>\n<p>AOP constructs are enabled by <strong><code>@EnableAspectJAutoProxy<\/code><\/strong>.<\/p>\n<p>But such AOP constructs may be problematic if we combine Mockito for mocking with Spring AOP. It is because both use CGLIB to proxy real instances and when Mockito proxy is wrapped into Spring proxy, we can experience type mismatch problems. These can be mitigated by configuring bean\u2019s scope with\u00a0<strong><code>ScopedProxyMode.TARGET_CLASS<\/code><\/strong>, but Mockito <strong><code>verify<\/code><code>()<\/code><\/strong> calls still fail with <strong><code>NotAMockException<\/code><\/strong>. Such problems can be seen if we enable <strong><code>aop<\/code><\/strong> profile for <strong><code>UserServiceITest<\/code><\/strong>.<\/p>\n<h2>Mock Spring bean proxied by Spring AOP<\/h2>\n<p>To overcome these problems, we will wrap mock into this Spring bean:<\/p>\n<pre class=\" brush:java\">package net.lkrnac.blog.testing.mockbeanv2.aoptesting;\r\n\r\nimport org.mockito.Mockito;\r\nimport org.springframework.context.annotation.Primary;\r\nimport org.springframework.context.annotation.Profile;\r\nimport org.springframework.stereotype.Repository;\r\n\r\nimport lombok.Getter;\r\nimport net.lkrnac.blog.testing.mockbeanv2.beans.AddressDao;\r\n\r\n@Primary\r\n@Repository\r\n@Profile(\"AddressService-aop-mock-test\")\r\npublic class AddressDaoMock extends AddressDao{\r\n\u00a0\u00a0 \u00a0@Getter\r\n\u00a0\u00a0 \u00a0private AddressDao mockDelegate = Mockito.mock(AddressDao.class);\r\n\u00a0\u00a0 \u00a0\r\n\u00a0\u00a0 \u00a0public String readAddress(String userName) {\r\n\u00a0\u00a0 \u00a0\u00a0\u00a0 \u00a0return mockDelegate.readAddress(userName);\r\n\u00a0\u00a0 \u00a0}\r\n}<\/pre>\n<p><strong><code>@Primary<\/code><\/strong> annotation makes sure that this bean will take precedence before real <strong><code>AddressDao<\/code><\/strong> bean during injection. To make sure it will be applied only for specific test, we define profile <strong><code>AddressService-aop-mock-test<\/code><\/strong> for this bean. It inherits <strong><code>AddressDao<\/code><\/strong> class, so that it can act as full replacement of that type.<\/p>\n<p>In order to fake behavior, we define mock instance of type <strong><code>AddressDao<\/code><\/strong>, which is exposed via getter defined by Lombok\u2019s <strong><code>@Getter<\/code><\/strong> annotation. We also implement <code><strong>readAddress()<\/strong><\/code> method which is expected to be called during test. This method just delegates the call to mock instance.<\/p>\n<p>The test where this mock is used can look like this:<\/p>\n<pre class=\" brush:java\">@ActiveProfiles({\"AddressService-aop-mock-test\", \"aop\"})\r\n@RunWith(SpringJUnit4ClassRunner.class)\r\n@SpringApplicationConfiguration(AopApplication.class)\r\npublic class AddressServiceAopMockITest {\r\n\u00a0\u00a0 \u00a0@Autowired\r\n\u00a0\u00a0 \u00a0private AddressService addressService; \r\n\r\n\u00a0\u00a0 \u00a0@Autowired\r\n\u00a0\u00a0 \u00a0private AddressDao addressDao;\r\n\u00a0\u00a0 \u00a0\r\n\u00a0\u00a0 \u00a0@Test\r\n\u00a0\u00a0 \u00a0public void testGetAddressForUser() {\r\n\u00a0\u00a0 \u00a0\u00a0\u00a0 \u00a0\/\/ GIVEN\r\n\u00a0\u00a0 \u00a0\u00a0\u00a0 \u00a0AddressDaoMock addressDaoMock = (AddressDaoMock) addressDao;\r\n\u00a0\u00a0 \u00a0\u00a0\u00a0 \u00a0Mockito.when(addressDaoMock.getMockDelegate().readAddress(\"john\"))\r\n\u00a0\u00a0 \u00a0\u00a0\u00a0 \u00a0\u00a0\u00a0 \u00a0.thenReturn(\"5 Bright Corner\");\r\n\u00a0\r\n\u00a0\u00a0 \u00a0\u00a0\u00a0 \u00a0\/\/ WHEN \r\n\u00a0\u00a0 \u00a0\u00a0\u00a0 \u00a0String actualAddress = addressService.getAddressForUser(\"john\");\r\n\u00a0\r\n\u00a0\u00a0 \u00a0\u00a0\u00a0 \u00a0\/\/ THEN \u00a0\r\n\u00a0\u00a0 \u00a0\u00a0\u00a0 \u00a0Assert.assertEquals(\"5 Bright Corner\", actualAddress);\r\n\u00a0\u00a0 \u00a0}\r\n}<\/pre>\n<p>In the test we define <strong><code>AddressService-aop-mock-test<\/code><\/strong> profile to activate <strong><code>AddressDaoMock<\/code><\/strong> and <strong><code>aop<\/code><\/strong> profile to activate <strong><code>AddressLogger<\/code><\/strong> AOP aspect. For testing, we autowire testing bean <strong><code>addressService<\/code><\/strong> and its faked dependency <strong><code>addressDao<\/code><\/strong>. As we know, <strong><code>addressDao<\/code><\/strong> will be of type <code><strong>AddressDaoMock<\/strong><\/code>, because this bean was marked as <strong><code>@Primary<\/code><\/strong>. Therefore we can cast it and record behavior into <strong><code>mockDelegate<\/code><\/strong>.<\/p>\n<p>When we call testing method, recorded behavior should be used because we expect testing method to use <strong><code>AddressDao<\/code><\/strong> dependency.<\/p>\n<h2>Spy on Spring bean proxied by Spring AOP<\/h2>\n<p>Similar pattern can be used for spying the real implementation. This is how our spy can look like:<\/p>\n<pre class=\" brush:java\">package net.lkrnac.blog.testing.mockbeanv2.aoptesting;\r\n\r\nimport org.mockito.Mockito;\r\nimport org.springframework.beans.factory.annotation.Autowired;\r\nimport org.springframework.context.annotation.Primary;\r\nimport org.springframework.context.annotation.Profile;\r\nimport org.springframework.stereotype.Service;\r\n\r\nimport lombok.Getter;\r\nimport net.lkrnac.blog.testing.mockbeanv2.beans.AddressDao;\r\nimport net.lkrnac.blog.testing.mockbeanv2.beans.AddressService;\r\n\r\n@Primary\r\n@Service\r\n@Profile(\"UserService-aop-test\")\r\npublic class AddressServiceSpy extends AddressService{\r\n\u00a0\u00a0 \u00a0@Getter\r\n\u00a0\u00a0 \u00a0private AddressService spyDelegate;\r\n\u00a0\u00a0 \u00a0\r\n\u00a0\u00a0 \u00a0@Autowired\r\n\u00a0\u00a0 \u00a0public AddressServiceSpy(AddressDao addressDao) {\r\n\u00a0\u00a0 \u00a0\u00a0\u00a0 \u00a0super(null);\r\n\u00a0\u00a0 \u00a0\u00a0\u00a0 \u00a0spyDelegate = Mockito.spy(new AddressService(addressDao));\r\n\u00a0\u00a0 \u00a0}\r\n\u00a0\u00a0 \u00a0\r\n\u00a0\u00a0 \u00a0public String getAddressForUser(String userName){\r\n\u00a0\u00a0 \u00a0\u00a0\u00a0 \u00a0return spyDelegate.getAddressForUser(userName);\r\n\u00a0\u00a0 \u00a0}\r\n}<\/pre>\n<p>As we can see this spy is very similar to <strong><code>AddressDaoMock<\/code><\/strong>. But in this case real bean is using constructor injection to autowire its dependency. Therefore we\u2019ll need to define non-default constructor and do constructor injection also. But we wouldn\u2019t pass injected dependency into parent constructor.<\/p>\n<p>To enable spying on real object, we construct new instance with all the dependencies, wrap it into Mockito spy instance and store it into <strong><code>spyDelegate<\/code><\/strong> property. We expect call of method <strong><code>getAddressForUser()<\/code><\/strong> during test, therefore we delegate this call to <strong><code>spyDelegate<\/code><\/strong>. This property can be accessed in test via getter defined by Lombok\u2019s <strong><code>@Getter<\/code><\/strong> annotation.<\/p>\n<p>Test itself would look like this:<\/p>\n<pre class=\" brush:java\">@ActiveProfiles({\"UserService-aop-test\", \"aop\"})\r\n@RunWith(SpringJUnit4ClassRunner.class)\r\n@SpringApplicationConfiguration(AopApplication.class)\r\npublic class UserServiceAopITest {\r\n\u00a0\u00a0 \u00a0@Autowired\r\n\u00a0\u00a0 \u00a0private UserService userService;\r\n\r\n\u00a0\u00a0 \u00a0@Autowired\r\n\u00a0\u00a0 \u00a0private AddressService addressService;\r\n\u00a0\u00a0 \u00a0\r\n\u00a0\u00a0 \u00a0@Test\r\n\u00a0\u00a0 \u00a0public void testGetUserDetails() {\r\n\u00a0\u00a0 \u00a0\u00a0\u00a0 \u00a0\/\/ GIVEN\r\n\u00a0\u00a0 \u00a0\u00a0\u00a0 \u00a0AddressServiceSpy addressServiceSpy = (AddressServiceSpy) addressService;\r\n\r\n\u00a0\u00a0 \u00a0\u00a0\u00a0 \u00a0\/\/ WHEN\r\n\u00a0\u00a0 \u00a0\u00a0\u00a0 \u00a0String actualUserDetails = userService.getUserDetails(\"john\");\r\n\u00a0 \r\n\u00a0\u00a0 \u00a0\u00a0\u00a0 \u00a0\/\/ THEN \r\n\u00a0\u00a0 \u00a0\u00a0\u00a0 \u00a0Assert.assertEquals(\"User john, 3 Dark Corner\", actualUserDetails);\r\n\u00a0\u00a0 \u00a0\u00a0\u00a0 \u00a0Mockito.verify(addressServiceSpy.getSpyDelegate()).getAddressForUser(\"john\");\r\n\u00a0\u00a0 \u00a0}\r\n}<\/pre>\n<p>It is very straight forward. Profile <strong><code>UserService-aop-test<\/code><\/strong> ensures that <strong><code>AddressServiceSpy<\/code><\/strong> will be scanned. Profile <strong><code>aop<\/code><\/strong> ensures same for <strong><code>AddressLogger<\/code><\/strong> aspect. When we autowire testing object <strong><code>UserService<\/code><\/strong> and its dependency <strong><code>AddressService<\/code><\/strong>, we know that we can cast it to <strong><code>AddressServiceSpy<\/code><\/strong> and verify the call on its <strong><code>spyDelegate<\/code><\/strong> property after calling the testing method.<\/p>\n<h2>Fake Spring bean proxied by Spring AOP<\/h2>\n<p>It is obvious that delegating calls into Mockito mocks or spies complicates the testing. These patterns are often overkill if we simply need to fake the logic. We can use such fake in that case:<\/p>\n<pre class=\" brush:java\">@Primary\r\n@Repository\r\n@Profile(\"AddressService-aop-fake-test\")\r\npublic class AddressDaoFake extends AddressDao{\r\n\u00a0\u00a0 \u00a0public String readAddress(String userName) {\r\n\u00a0\u00a0 \u00a0\u00a0\u00a0 \u00a0return userName + \"'s address\";\r\n\u00a0\u00a0 \u00a0}\r\n}<\/pre>\n<p>and used it for testing this way:<\/p>\n<pre class=\" brush:java\">@ActiveProfiles({\"AddressService-aop-fake-test\", \"aop\"})\r\n@RunWith(SpringJUnit4ClassRunner.class)\r\n@SpringApplicationConfiguration(AopApplication.class)\r\npublic class AddressServiceAopFakeITest {\r\n\u00a0\u00a0 \u00a0@Autowired\r\n\u00a0\u00a0 \u00a0private AddressService addressService; \r\n\r\n\u00a0\u00a0 \u00a0@Test\r\n\u00a0\u00a0 \u00a0public void testGetAddressForUser() {\r\n\u00a0\u00a0 \u00a0\u00a0\u00a0 \u00a0\/\/ GIVEN - Spring context\r\n\u00a0\r\n\u00a0\u00a0 \u00a0\u00a0\u00a0 \u00a0\/\/ WHEN \r\n\u00a0\u00a0 \u00a0\u00a0\u00a0 \u00a0String actualAddress = addressService.getAddressForUser(\"john\");\r\n\u00a0\r\n\u00a0\u00a0 \u00a0\u00a0\u00a0 \u00a0\/\/ THEN \u00a0\r\n\u00a0\u00a0 \u00a0\u00a0\u00a0 \u00a0Assert.assertEquals(\"john's address\", actualAddress);\r\n\u00a0\u00a0 \u00a0}\r\n}<\/pre>\n<p>I don\u2019t think this test needs explanation.<\/p>\n<ul>\n<li><a href=\"https:\/\/github.com\/lkrnac\/blog-2015-11-mock-spring-bean-v2\">Source code for these examples is hosted on Github.<\/a><\/li>\n<\/ul>\n<div class=\"attribution\">\n<table>\n<tbody>\n<tr>\n<td><span class=\"reference\">Reference: <\/span><\/td>\n<td><a href=\"http:\/\/lkrnac.net\/blog\/2015\/12\/mock-spring-bean-v2\/\">How to mock Spring bean (version 2)<\/a> from our <a href=\"http:\/\/www.javacodegeeks.com\/join-us\/jcg\/\">JCG partner<\/a> Lubos Krnac at the <a href=\"http:\/\/lkrnac.net\/blog\/\">Lubos Krnac Java blog<\/a> blog.<\/td>\n<\/tr>\n<\/tbody>\n<\/table>\n<\/div>\n","protected":false},"excerpt":{"rendered":"<p>About a year ago, I wrote a blog post how to mock Spring Bean. Patterns described there were little bit invasive to the production code.\u00a0 As one of the readers Colin correctly pointed out in comment, there is better alternative to spy\/mock Spring bean based on @Profile annotation. This blog post is going to describe &hellip;<\/p>\n","protected":false},"author":534,"featured_media":240,"comment_status":"open","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[8],"tags":[30],"class_list":["post-50846","post","type-post","status-publish","format-standard","has-post-thumbnail","hentry","category-enterprise-java","tag-spring"],"yoast_head":"<!-- This site is optimized with the Yoast SEO plugin v27.5 - https:\/\/yoast.com\/product\/yoast-seo-wordpress\/ -->\n<title>How to mock Spring bean (version 2) - Java Code Geeks<\/title>\n<meta name=\"description\" content=\"About a year ago, I wrote a blog post how to mock Spring Bean. Patterns described there were little bit invasive to the production code.\u00a0 As one of the\" \/>\n<meta name=\"robots\" content=\"index, follow, max-snippet:-1, max-image-preview:large, max-video-preview:-1\" \/>\n<link rel=\"canonical\" href=\"https:\/\/www.javacodegeeks.com\/2016\/01\/mock-spring-bean-version-2.html\" \/>\n<meta property=\"og:locale\" content=\"en_US\" \/>\n<meta property=\"og:type\" content=\"article\" \/>\n<meta property=\"og:title\" content=\"How to mock Spring bean (version 2) - Java Code Geeks\" \/>\n<meta property=\"og:description\" content=\"About a year ago, I wrote a blog post how to mock Spring Bean. Patterns described there were little bit invasive to the production code.\u00a0 As one of the\" \/>\n<meta property=\"og:url\" content=\"https:\/\/www.javacodegeeks.com\/2016\/01\/mock-spring-bean-version-2.html\" \/>\n<meta property=\"og:site_name\" content=\"Java Code Geeks\" \/>\n<meta property=\"article:publisher\" content=\"https:\/\/www.facebook.com\/javacodegeeks\" \/>\n<meta property=\"article:published_time\" content=\"2016-01-08T11:00:39+00:00\" \/>\n<meta property=\"og:image\" content=\"https:\/\/www.javacodegeeks.com\/wp-content\/uploads\/2012\/10\/spring-logo.jpg\" \/>\n\t<meta property=\"og:image:width\" content=\"150\" \/>\n\t<meta property=\"og:image:height\" content=\"150\" \/>\n\t<meta property=\"og:image:type\" content=\"image\/jpeg\" \/>\n<meta name=\"author\" content=\"Lubos Krnac\" \/>\n<meta name=\"twitter:card\" content=\"summary_large_image\" \/>\n<meta name=\"twitter:creator\" content=\"@https:\/\/twitter.com\/luboskrnac\" \/>\n<meta name=\"twitter:site\" content=\"@javacodegeeks\" \/>\n<meta name=\"twitter:label1\" content=\"Written by\" \/>\n\t<meta name=\"twitter:data1\" content=\"Lubos Krnac\" \/>\n\t<meta name=\"twitter:label2\" content=\"Est. reading time\" \/>\n\t<meta name=\"twitter:data2\" content=\"9 minutes\" \/>\n<script type=\"application\/ld+json\" class=\"yoast-schema-graph\">{\"@context\":\"https:\\\/\\\/schema.org\",\"@graph\":[{\"@type\":\"Article\",\"@id\":\"https:\\\/\\\/www.javacodegeeks.com\\\/2016\\\/01\\\/mock-spring-bean-version-2.html#article\",\"isPartOf\":{\"@id\":\"https:\\\/\\\/www.javacodegeeks.com\\\/2016\\\/01\\\/mock-spring-bean-version-2.html\"},\"author\":{\"name\":\"Lubos Krnac\",\"@id\":\"https:\\\/\\\/www.javacodegeeks.com\\\/#\\\/schema\\\/person\\\/c37fdcf9c17dcd577b0b278db3fa1fb7\"},\"headline\":\"How to mock Spring bean (version 2)\",\"datePublished\":\"2016-01-08T11:00:39+00:00\",\"mainEntityOfPage\":{\"@id\":\"https:\\\/\\\/www.javacodegeeks.com\\\/2016\\\/01\\\/mock-spring-bean-version-2.html\"},\"wordCount\":1156,\"commentCount\":0,\"publisher\":{\"@id\":\"https:\\\/\\\/www.javacodegeeks.com\\\/#organization\"},\"image\":{\"@id\":\"https:\\\/\\\/www.javacodegeeks.com\\\/2016\\\/01\\\/mock-spring-bean-version-2.html#primaryimage\"},\"thumbnailUrl\":\"https:\\\/\\\/www.javacodegeeks.com\\\/wp-content\\\/uploads\\\/2012\\\/10\\\/spring-logo.jpg\",\"keywords\":[\"Spring\"],\"articleSection\":[\"Enterprise Java\"],\"inLanguage\":\"en-US\",\"potentialAction\":[{\"@type\":\"CommentAction\",\"name\":\"Comment\",\"target\":[\"https:\\\/\\\/www.javacodegeeks.com\\\/2016\\\/01\\\/mock-spring-bean-version-2.html#respond\"]}]},{\"@type\":\"WebPage\",\"@id\":\"https:\\\/\\\/www.javacodegeeks.com\\\/2016\\\/01\\\/mock-spring-bean-version-2.html\",\"url\":\"https:\\\/\\\/www.javacodegeeks.com\\\/2016\\\/01\\\/mock-spring-bean-version-2.html\",\"name\":\"How to mock Spring bean (version 2) - Java Code Geeks\",\"isPartOf\":{\"@id\":\"https:\\\/\\\/www.javacodegeeks.com\\\/#website\"},\"primaryImageOfPage\":{\"@id\":\"https:\\\/\\\/www.javacodegeeks.com\\\/2016\\\/01\\\/mock-spring-bean-version-2.html#primaryimage\"},\"image\":{\"@id\":\"https:\\\/\\\/www.javacodegeeks.com\\\/2016\\\/01\\\/mock-spring-bean-version-2.html#primaryimage\"},\"thumbnailUrl\":\"https:\\\/\\\/www.javacodegeeks.com\\\/wp-content\\\/uploads\\\/2012\\\/10\\\/spring-logo.jpg\",\"datePublished\":\"2016-01-08T11:00:39+00:00\",\"description\":\"About a year ago, I wrote a blog post how to mock Spring Bean. Patterns described there were little bit invasive to the production code.\u00a0 As one of the\",\"breadcrumb\":{\"@id\":\"https:\\\/\\\/www.javacodegeeks.com\\\/2016\\\/01\\\/mock-spring-bean-version-2.html#breadcrumb\"},\"inLanguage\":\"en-US\",\"potentialAction\":[{\"@type\":\"ReadAction\",\"target\":[\"https:\\\/\\\/www.javacodegeeks.com\\\/2016\\\/01\\\/mock-spring-bean-version-2.html\"]}]},{\"@type\":\"ImageObject\",\"inLanguage\":\"en-US\",\"@id\":\"https:\\\/\\\/www.javacodegeeks.com\\\/2016\\\/01\\\/mock-spring-bean-version-2.html#primaryimage\",\"url\":\"https:\\\/\\\/www.javacodegeeks.com\\\/wp-content\\\/uploads\\\/2012\\\/10\\\/spring-logo.jpg\",\"contentUrl\":\"https:\\\/\\\/www.javacodegeeks.com\\\/wp-content\\\/uploads\\\/2012\\\/10\\\/spring-logo.jpg\",\"width\":150,\"height\":150,\"caption\":\"spring-interview-questions-answers\"},{\"@type\":\"BreadcrumbList\",\"@id\":\"https:\\\/\\\/www.javacodegeeks.com\\\/2016\\\/01\\\/mock-spring-bean-version-2.html#breadcrumb\",\"itemListElement\":[{\"@type\":\"ListItem\",\"position\":1,\"name\":\"Home\",\"item\":\"https:\\\/\\\/www.javacodegeeks.com\\\/\"},{\"@type\":\"ListItem\",\"position\":2,\"name\":\"Java\",\"item\":\"https:\\\/\\\/www.javacodegeeks.com\\\/category\\\/java\"},{\"@type\":\"ListItem\",\"position\":3,\"name\":\"Enterprise Java\",\"item\":\"https:\\\/\\\/www.javacodegeeks.com\\\/category\\\/java\\\/enterprise-java\"},{\"@type\":\"ListItem\",\"position\":4,\"name\":\"How to mock Spring bean (version 2)\"}]},{\"@type\":\"WebSite\",\"@id\":\"https:\\\/\\\/www.javacodegeeks.com\\\/#website\",\"url\":\"https:\\\/\\\/www.javacodegeeks.com\\\/\",\"name\":\"Java Code Geeks\",\"description\":\"Java Developers Resource Center\",\"publisher\":{\"@id\":\"https:\\\/\\\/www.javacodegeeks.com\\\/#organization\"},\"alternateName\":\"JCG\",\"potentialAction\":[{\"@type\":\"SearchAction\",\"target\":{\"@type\":\"EntryPoint\",\"urlTemplate\":\"https:\\\/\\\/www.javacodegeeks.com\\\/?s={search_term_string}\"},\"query-input\":{\"@type\":\"PropertyValueSpecification\",\"valueRequired\":true,\"valueName\":\"search_term_string\"}}],\"inLanguage\":\"en-US\"},{\"@type\":\"Organization\",\"@id\":\"https:\\\/\\\/www.javacodegeeks.com\\\/#organization\",\"name\":\"Exelixis Media P.C.\",\"url\":\"https:\\\/\\\/www.javacodegeeks.com\\\/\",\"logo\":{\"@type\":\"ImageObject\",\"inLanguage\":\"en-US\",\"@id\":\"https:\\\/\\\/www.javacodegeeks.com\\\/#\\\/schema\\\/logo\\\/image\\\/\",\"url\":\"https:\\\/\\\/www.javacodegeeks.com\\\/wp-content\\\/uploads\\\/2022\\\/06\\\/exelixis-logo.png\",\"contentUrl\":\"https:\\\/\\\/www.javacodegeeks.com\\\/wp-content\\\/uploads\\\/2022\\\/06\\\/exelixis-logo.png\",\"width\":864,\"height\":246,\"caption\":\"Exelixis Media P.C.\"},\"image\":{\"@id\":\"https:\\\/\\\/www.javacodegeeks.com\\\/#\\\/schema\\\/logo\\\/image\\\/\"},\"sameAs\":[\"https:\\\/\\\/www.facebook.com\\\/javacodegeeks\",\"https:\\\/\\\/x.com\\\/javacodegeeks\"]},{\"@type\":\"Person\",\"@id\":\"https:\\\/\\\/www.javacodegeeks.com\\\/#\\\/schema\\\/person\\\/c37fdcf9c17dcd577b0b278db3fa1fb7\",\"name\":\"Lubos Krnac\",\"image\":{\"@type\":\"ImageObject\",\"inLanguage\":\"en-US\",\"@id\":\"https:\\\/\\\/secure.gravatar.com\\\/avatar\\\/de54fe70007a5ff7a805ec6c874812ec129162cb080f66e7a14a05df13da44d1?s=96&d=mm&r=g\",\"url\":\"https:\\\/\\\/secure.gravatar.com\\\/avatar\\\/de54fe70007a5ff7a805ec6c874812ec129162cb080f66e7a14a05df13da44d1?s=96&d=mm&r=g\",\"contentUrl\":\"https:\\\/\\\/secure.gravatar.com\\\/avatar\\\/de54fe70007a5ff7a805ec6c874812ec129162cb080f66e7a14a05df13da44d1?s=96&d=mm&r=g\",\"caption\":\"Lubos Krnac\"},\"description\":\"Lubos is a Java\\\/JavaScript developer\\\/Tech Lead and Automation enthusiast. His religion is to constantly improve his developments skills and learn new approaches. He believes TDD drives better design and nicely decoupled code. Past experience includes C++, Assembler and C#.\",\"sameAs\":[\"http:\\\/\\\/lkrnac.net\\\/\",\"http:\\\/\\\/www.linkedin.com\\\/pub\\\/lubos-krnac\\\/27\\\/21a\\\/b2\",\"https:\\\/\\\/x.com\\\/https:\\\/\\\/twitter.com\\\/luboskrnac\"],\"url\":\"https:\\\/\\\/www.javacodegeeks.com\\\/author\\\/lubos-krnac\"}]}<\/script>\n<!-- \/ Yoast SEO plugin. -->","yoast_head_json":{"title":"How to mock Spring bean (version 2) - Java Code Geeks","description":"About a year ago, I wrote a blog post how to mock Spring Bean. Patterns described there were little bit invasive to the production code.\u00a0 As one of the","robots":{"index":"index","follow":"follow","max-snippet":"max-snippet:-1","max-image-preview":"max-image-preview:large","max-video-preview":"max-video-preview:-1"},"canonical":"https:\/\/www.javacodegeeks.com\/2016\/01\/mock-spring-bean-version-2.html","og_locale":"en_US","og_type":"article","og_title":"How to mock Spring bean (version 2) - Java Code Geeks","og_description":"About a year ago, I wrote a blog post how to mock Spring Bean. Patterns described there were little bit invasive to the production code.\u00a0 As one of the","og_url":"https:\/\/www.javacodegeeks.com\/2016\/01\/mock-spring-bean-version-2.html","og_site_name":"Java Code Geeks","article_publisher":"https:\/\/www.facebook.com\/javacodegeeks","article_published_time":"2016-01-08T11:00:39+00:00","og_image":[{"width":150,"height":150,"url":"https:\/\/www.javacodegeeks.com\/wp-content\/uploads\/2012\/10\/spring-logo.jpg","type":"image\/jpeg"}],"author":"Lubos Krnac","twitter_card":"summary_large_image","twitter_creator":"@https:\/\/twitter.com\/luboskrnac","twitter_site":"@javacodegeeks","twitter_misc":{"Written by":"Lubos Krnac","Est. reading time":"9 minutes"},"schema":{"@context":"https:\/\/schema.org","@graph":[{"@type":"Article","@id":"https:\/\/www.javacodegeeks.com\/2016\/01\/mock-spring-bean-version-2.html#article","isPartOf":{"@id":"https:\/\/www.javacodegeeks.com\/2016\/01\/mock-spring-bean-version-2.html"},"author":{"name":"Lubos Krnac","@id":"https:\/\/www.javacodegeeks.com\/#\/schema\/person\/c37fdcf9c17dcd577b0b278db3fa1fb7"},"headline":"How to mock Spring bean (version 2)","datePublished":"2016-01-08T11:00:39+00:00","mainEntityOfPage":{"@id":"https:\/\/www.javacodegeeks.com\/2016\/01\/mock-spring-bean-version-2.html"},"wordCount":1156,"commentCount":0,"publisher":{"@id":"https:\/\/www.javacodegeeks.com\/#organization"},"image":{"@id":"https:\/\/www.javacodegeeks.com\/2016\/01\/mock-spring-bean-version-2.html#primaryimage"},"thumbnailUrl":"https:\/\/www.javacodegeeks.com\/wp-content\/uploads\/2012\/10\/spring-logo.jpg","keywords":["Spring"],"articleSection":["Enterprise Java"],"inLanguage":"en-US","potentialAction":[{"@type":"CommentAction","name":"Comment","target":["https:\/\/www.javacodegeeks.com\/2016\/01\/mock-spring-bean-version-2.html#respond"]}]},{"@type":"WebPage","@id":"https:\/\/www.javacodegeeks.com\/2016\/01\/mock-spring-bean-version-2.html","url":"https:\/\/www.javacodegeeks.com\/2016\/01\/mock-spring-bean-version-2.html","name":"How to mock Spring bean (version 2) - Java Code Geeks","isPartOf":{"@id":"https:\/\/www.javacodegeeks.com\/#website"},"primaryImageOfPage":{"@id":"https:\/\/www.javacodegeeks.com\/2016\/01\/mock-spring-bean-version-2.html#primaryimage"},"image":{"@id":"https:\/\/www.javacodegeeks.com\/2016\/01\/mock-spring-bean-version-2.html#primaryimage"},"thumbnailUrl":"https:\/\/www.javacodegeeks.com\/wp-content\/uploads\/2012\/10\/spring-logo.jpg","datePublished":"2016-01-08T11:00:39+00:00","description":"About a year ago, I wrote a blog post how to mock Spring Bean. Patterns described there were little bit invasive to the production code.\u00a0 As one of the","breadcrumb":{"@id":"https:\/\/www.javacodegeeks.com\/2016\/01\/mock-spring-bean-version-2.html#breadcrumb"},"inLanguage":"en-US","potentialAction":[{"@type":"ReadAction","target":["https:\/\/www.javacodegeeks.com\/2016\/01\/mock-spring-bean-version-2.html"]}]},{"@type":"ImageObject","inLanguage":"en-US","@id":"https:\/\/www.javacodegeeks.com\/2016\/01\/mock-spring-bean-version-2.html#primaryimage","url":"https:\/\/www.javacodegeeks.com\/wp-content\/uploads\/2012\/10\/spring-logo.jpg","contentUrl":"https:\/\/www.javacodegeeks.com\/wp-content\/uploads\/2012\/10\/spring-logo.jpg","width":150,"height":150,"caption":"spring-interview-questions-answers"},{"@type":"BreadcrumbList","@id":"https:\/\/www.javacodegeeks.com\/2016\/01\/mock-spring-bean-version-2.html#breadcrumb","itemListElement":[{"@type":"ListItem","position":1,"name":"Home","item":"https:\/\/www.javacodegeeks.com\/"},{"@type":"ListItem","position":2,"name":"Java","item":"https:\/\/www.javacodegeeks.com\/category\/java"},{"@type":"ListItem","position":3,"name":"Enterprise Java","item":"https:\/\/www.javacodegeeks.com\/category\/java\/enterprise-java"},{"@type":"ListItem","position":4,"name":"How to mock Spring bean (version 2)"}]},{"@type":"WebSite","@id":"https:\/\/www.javacodegeeks.com\/#website","url":"https:\/\/www.javacodegeeks.com\/","name":"Java Code Geeks","description":"Java Developers Resource Center","publisher":{"@id":"https:\/\/www.javacodegeeks.com\/#organization"},"alternateName":"JCG","potentialAction":[{"@type":"SearchAction","target":{"@type":"EntryPoint","urlTemplate":"https:\/\/www.javacodegeeks.com\/?s={search_term_string}"},"query-input":{"@type":"PropertyValueSpecification","valueRequired":true,"valueName":"search_term_string"}}],"inLanguage":"en-US"},{"@type":"Organization","@id":"https:\/\/www.javacodegeeks.com\/#organization","name":"Exelixis Media P.C.","url":"https:\/\/www.javacodegeeks.com\/","logo":{"@type":"ImageObject","inLanguage":"en-US","@id":"https:\/\/www.javacodegeeks.com\/#\/schema\/logo\/image\/","url":"https:\/\/www.javacodegeeks.com\/wp-content\/uploads\/2022\/06\/exelixis-logo.png","contentUrl":"https:\/\/www.javacodegeeks.com\/wp-content\/uploads\/2022\/06\/exelixis-logo.png","width":864,"height":246,"caption":"Exelixis Media P.C."},"image":{"@id":"https:\/\/www.javacodegeeks.com\/#\/schema\/logo\/image\/"},"sameAs":["https:\/\/www.facebook.com\/javacodegeeks","https:\/\/x.com\/javacodegeeks"]},{"@type":"Person","@id":"https:\/\/www.javacodegeeks.com\/#\/schema\/person\/c37fdcf9c17dcd577b0b278db3fa1fb7","name":"Lubos Krnac","image":{"@type":"ImageObject","inLanguage":"en-US","@id":"https:\/\/secure.gravatar.com\/avatar\/de54fe70007a5ff7a805ec6c874812ec129162cb080f66e7a14a05df13da44d1?s=96&d=mm&r=g","url":"https:\/\/secure.gravatar.com\/avatar\/de54fe70007a5ff7a805ec6c874812ec129162cb080f66e7a14a05df13da44d1?s=96&d=mm&r=g","contentUrl":"https:\/\/secure.gravatar.com\/avatar\/de54fe70007a5ff7a805ec6c874812ec129162cb080f66e7a14a05df13da44d1?s=96&d=mm&r=g","caption":"Lubos Krnac"},"description":"Lubos is a Java\/JavaScript developer\/Tech Lead and Automation enthusiast. His religion is to constantly improve his developments skills and learn new approaches. He believes TDD drives better design and nicely decoupled code. Past experience includes C++, Assembler and C#.","sameAs":["http:\/\/lkrnac.net\/","http:\/\/www.linkedin.com\/pub\/lubos-krnac\/27\/21a\/b2","https:\/\/x.com\/https:\/\/twitter.com\/luboskrnac"],"url":"https:\/\/www.javacodegeeks.com\/author\/lubos-krnac"}]}},"_links":{"self":[{"href":"https:\/\/www.javacodegeeks.com\/wp-json\/wp\/v2\/posts\/50846","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/www.javacodegeeks.com\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/www.javacodegeeks.com\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/www.javacodegeeks.com\/wp-json\/wp\/v2\/users\/534"}],"replies":[{"embeddable":true,"href":"https:\/\/www.javacodegeeks.com\/wp-json\/wp\/v2\/comments?post=50846"}],"version-history":[{"count":0,"href":"https:\/\/www.javacodegeeks.com\/wp-json\/wp\/v2\/posts\/50846\/revisions"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/www.javacodegeeks.com\/wp-json\/wp\/v2\/media\/240"}],"wp:attachment":[{"href":"https:\/\/www.javacodegeeks.com\/wp-json\/wp\/v2\/media?parent=50846"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/www.javacodegeeks.com\/wp-json\/wp\/v2\/categories?post=50846"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/www.javacodegeeks.com\/wp-json\/wp\/v2\/tags?post=50846"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}