Commits

Marcin Grzejszczak  committed 761c4f5

[Mockito - Injecting Test Doubles in Spring] Initial commit

  • Participants
  • Parent commits 9f0f64d

Comments (0)

Files changed (12)

File Unit Testing/Mockito - Injecting Test Doubles in Spring/pom.xml

+<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
+	xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
+	<modelVersion>4.0.0</modelVersion>
+	<groupId>com.blogspot.toomuchcoding</groupId>
+	<artifactId>mockito-injecting_test_doubles_in_spring</artifactId>
+	<version>0.0.1-SNAPSHOT</version>
+
+	<properties>
+		<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
+		<maven.compiler.source>1.6</maven.compiler.source>
+		<maven.compiler.target>1.6</maven.compiler.target>
+		<spring.version>3.1.1.RELEASE</spring.version>
+    </properties>
+	<repositories>
+		<repository>
+			<id>spring-release</id>
+			<url>http://maven.springframework.org/release</url>
+		</repository>
+		<repository>
+			<id>maven-us-nuxeo</id>
+			<url>https://maven-us.nuxeo.org/nexus/content/groups/public</url>
+		</repository>
+	</repositories>
+
+	<dependencies>
+		<!-- Spring -->
+		<dependency>
+			<groupId>org.springframework</groupId>
+			<artifactId>spring-core</artifactId>
+			<version>${spring.version}</version>
+		</dependency>
+        <dependency>
+            <groupId>org.springframework</groupId>
+            <artifactId>spring-context</artifactId>
+            <version>${spring.version}</version>
+        </dependency>
+        <dependency>
+            <groupId>org.springframework</groupId>
+            <artifactId>spring-test</artifactId>
+            <version>${spring.version}</version>
+        </dependency>
+        <dependency>
+            <groupId>org.slf4j</groupId>
+            <artifactId>slf4j-api</artifactId>
+            <version>1.6.6</version>
+        </dependency>
+        <dependency>
+            <groupId>org.slf4j</groupId>
+            <artifactId>slf4j-log4j12</artifactId>
+            <version>1.6.6</version>
+        </dependency>
+		<dependency>
+			<groupId>junit</groupId>
+			<artifactId>junit</artifactId>
+			<version>4.10</version>
+		</dependency>
+		<dependency>
+            <groupId>org.mockito</groupId>
+            <artifactId>mockito-all</artifactId>
+            <version>1.9.5</version>
+            <scope>test</scope>
+        </dependency>
+    </dependencies>
+	
+	
+    <build>
+        <pluginManagement>
+            <plugins>
+                <plugin>
+                    <groupId>org.apache.maven.plugins</groupId>
+                    <artifactId>maven-compiler-plugin</artifactId>
+                    <version>2.5.1</version>
+                </plugin>
+            </plugins>
+        </pluginManagement>
+    </build>
+
+</project>

File Unit Testing/Mockito - Injecting Test Doubles in Spring/src/main/java/com/blogspot/toomuchcoding/model/Player.java

+package com.blogspot.toomuchcoding.model;
+
+import java.math.BigDecimal;
+
+/**
+ * User: mgrzejszczak
+ * Date: 08.08.13
+ * Time: 14:38
+ */
+public final class Player {
+    private final String playerName;
+    private final BigDecimal playerValue;
+
+    public Player(final String playerName, final BigDecimal playerValue) {
+        this.playerName = playerName;
+        this.playerValue = playerValue;
+    }
+
+    public String getPlayerName() {
+        return playerName;
+    }
+
+    public BigDecimal getPlayerValue() {
+        return playerValue;
+    }
+}

File Unit Testing/Mockito - Injecting Test Doubles in Spring/src/main/java/com/blogspot/toomuchcoding/processor/AbstractBeanPostProcessor.java

+package com.blogspot.toomuchcoding.processor;
+
+import org.springframework.beans.BeansException;
+import org.springframework.beans.factory.config.BeanPostProcessor;
+import org.springframework.context.ApplicationContext;
+import org.springframework.context.ApplicationContextAware;
+
+/**
+ * Created with IntelliJ IDEA.
+ * User: mgrzejszczak
+ * Date: 26.03.13
+ * Time: 13:14
+ */
+public abstract class AbstractBeanPostProcessor<T> implements BeanPostProcessor, ApplicationContextAware {
+
+    private Class<T> clazz;
+    protected ApplicationContext applicationContext;
+
+    public AbstractBeanPostProcessor(Class<T> clazz) {
+        this.clazz = clazz;
+    }
+
+    @Override
+    public Object postProcessAfterInitialization(Object bean, String name) throws BeansException {
+        checkConditions();
+        if (clazz.isAssignableFrom(bean.getClass())) {
+            return doAfter((T) bean);
+        }
+        return bean;
+    }
+
+    @Override
+    public Object postProcessBeforeInitialization(Object bean, String name) throws BeansException {
+        checkConditions();
+
+        if (clazz.isAssignableFrom(bean.getClass())) {
+            return doBefore((T) bean);
+        }
+        return bean;
+    }
+
+    private void checkConditions() {
+        if (clazz == null) {
+            throw new RuntimeException("Provide the interface for the post processor");
+        }
+    }
+
+    public abstract T doBefore(T bean);
+
+    public abstract T doAfter(T bean);
+
+    public void setApplicationContext(ApplicationContext applicationContext) {
+        this.applicationContext = applicationContext;
+    }
+}

File Unit Testing/Mockito - Injecting Test Doubles in Spring/src/main/java/com/blogspot/toomuchcoding/service/PlayerService.java

+package com.blogspot.toomuchcoding.service;
+
+import com.blogspot.toomuchcoding.model.Player;
+
+/**
+ * User: mgrzejszczak
+ * Date: 08.06.13
+ * Time: 18:59
+ */
+public interface PlayerService {
+    Player getPlayerByName(String playerName);
+}

File Unit Testing/Mockito - Injecting Test Doubles in Spring/src/main/java/com/blogspot/toomuchcoding/service/PlayerServiceImpl.java

+package com.blogspot.toomuchcoding.service;
+
+import com.blogspot.toomuchcoding.model.Player;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.stereotype.Service;
+
+/**
+ * User: mgrzejszczak
+ * Date: 08.06.13
+ * Time: 19:02
+ */
+@Service
+public class PlayerServiceImpl implements PlayerService {
+    private static final Logger LOGGER = LoggerFactory.getLogger(PlayerServiceImpl.class);
+
+    @Autowired
+    private PlayerWebService playerWebService;
+
+    @Override
+    public Player getPlayerByName(String playerName) {
+        LOGGER.debug(String.format("Logging the player web service name [%s]", playerWebService.getWebServiceName()));
+        return playerWebService.getPlayerByName(playerName);
+    }
+
+    public PlayerWebService getPlayerWebService() {
+        return playerWebService;
+    }
+
+    public void setPlayerWebService(PlayerWebService playerWebService) {
+        this.playerWebService = playerWebService;
+    }
+}

File Unit Testing/Mockito - Injecting Test Doubles in Spring/src/main/java/com/blogspot/toomuchcoding/service/PlayerWebService.java

+package com.blogspot.toomuchcoding.service;
+
+import com.blogspot.toomuchcoding.model.Player;
+
+/**
+ * User: mgrzejszczak
+ * Date: 08.08.13
+ * Time: 14:47
+ */
+public interface PlayerWebService {
+    String getWebServiceName();
+    Player getPlayerByName(String name);
+}

File Unit Testing/Mockito - Injecting Test Doubles in Spring/src/main/java/com/blogspot/toomuchcoding/service/PlayerWebServiceImpl.java

+package com.blogspot.toomuchcoding.service;
+
+import com.blogspot.toomuchcoding.model.Player;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+import org.springframework.stereotype.Service;
+
+import java.math.BigDecimal;
+
+/**
+ * User: mgrzejszczak
+ * Date: 08.08.13
+ * Time: 14:48
+ */
+@Service
+public class PlayerWebServiceImpl implements PlayerWebService {
+    private static final Logger LOGGER = LoggerFactory.getLogger(PlayerWebServiceImpl.class);
+    public static final String WEB_SERVICE_NAME = "SuperPlayerWebService";
+    public static final String SAMPLE_PLAYER_VALUE = "1000";
+
+    @Override
+    public String getWebServiceName() {
+        return WEB_SERVICE_NAME;
+    }
+
+    @Override
+    public Player getPlayerByName(String name) {
+        try {
+            LOGGER.debug("Simulating awaiting time for a response from a web service");
+            Thread.sleep(5000);
+        } catch (InterruptedException e) {
+            LOGGER.error(String.format("[%s] occurred while trying to make the thread sleep", e));
+        }
+        return new Player(name, new BigDecimal(SAMPLE_PLAYER_VALUE));
+    }
+}

File Unit Testing/Mockito - Injecting Test Doubles in Spring/src/main/resources/applicationContext.xml

+<?xml version="1.0" encoding="UTF-8"?>
+<beans xmlns="http://www.springframework.org/schema/beans"
+       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
+       xmlns:context="http://www.springframework.org/schema/context"
+       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
+                           http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd">
+
+    <context:component-scan base-package="com.blogspot.toomuchcoding"/>
+
+</beans>

File Unit Testing/Mockito - Injecting Test Doubles in Spring/src/main/resources/log4j.xml

+<?xml version="1.0" encoding="UTF-8"?>
+<!DOCTYPE log4j:configuration SYSTEM "log4j.dtd">
+<log4j:configuration xmlns:log4j="http://jakarta.apache.org/log4j/">
+
+	<!-- Appenders -->
+	<appender name="console" class="org.apache.log4j.ConsoleAppender">
+		<param name="Target" value="System.out" />
+		<layout class="org.apache.log4j.PatternLayout">
+			<param name="ConversionPattern" value="%d %-5p [%t] %c:%L %m%n" />
+		</layout>
+	</appender>
+	
+	<!-- Application Loggers -->
+	<logger name="com.blogspot">
+		<level value="DEBUG" />
+	</logger>
+	
+	<!-- 3rdparty Loggers -->
+	<logger name="org.springframework">
+		<level value="INFO" />
+	</logger>
+
+
+	<!-- Root Logger -->
+	<root>
+		<priority value="INFO" />
+		<appender-ref ref="console" />
+	</root>
+	
+</log4j:configuration>

File Unit Testing/Mockito - Injecting Test Doubles in Spring/src/test/java/com/blogspot/postprocessor/PlayerWebServicePostProcessor.java

+package com.blogspot.postprocessor;
+
+
+import com.blogspot.toomuchcoding.processor.AbstractBeanPostProcessor;
+import com.blogspot.toomuchcoding.service.PlayerWebService;
+import org.springframework.stereotype.Component;
+
+import static org.mockito.Mockito.spy;
+
+/**
+ * User: mpasinski
+ * Date: 07.05.13
+ * Time: 11:30
+ */
+@Component
+public class PlayerWebServicePostProcessor extends AbstractBeanPostProcessor<PlayerWebService> {
+    public PlayerWebServicePostProcessor() {
+        super(PlayerWebService.class);
+    }
+
+    @Override
+    public PlayerWebService doBefore(PlayerWebService bean) {
+        return spy(bean);
+    }
+
+    @Override
+    public PlayerWebService doAfter(PlayerWebService bean) {
+        return bean;
+    }
+}

File Unit Testing/Mockito - Injecting Test Doubles in Spring/src/test/java/com/blogspot/toomuchcoding/service/PlayerServiceImplTest.java

+package com.blogspot.toomuchcoding.service;
+
+import com.blogspot.toomuchcoding.model.Player;
+import org.junit.Test;
+import org.junit.runner.RunWith;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.test.context.ContextConfiguration;
+import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
+
+import java.math.BigDecimal;
+
+import static org.hamcrest.CoreMatchers.is;
+import static org.junit.Assert.assertThat;
+import static org.mockito.BDDMockito.doReturn;
+import static org.mockito.Mockito.verify;
+
+/**
+ * User: mgrzejszczak
+ * Date: 08.06.13
+ * Time: 19:26
+ */
+@RunWith(SpringJUnit4ClassRunner.class)
+@ContextConfiguration("classpath:testApplicationContext.xml")
+public class PlayerServiceImplTest {
+
+    public static final String PLAYER_NAME = "Lewandowski";
+    public static final BigDecimal PLAYER_VALUE = new BigDecimal("35000000");
+
+    @Autowired
+    PlayerWebService playerWebServiceSpy;
+
+    @Autowired
+    PlayerService objectUnderTest;
+
+    @Test
+    public void shouldReturnAPlayerFromPlayerWebService(){
+        //given
+        Player referencePlayer = new Player(PLAYER_NAME, PLAYER_VALUE);
+        doReturn(referencePlayer).when(playerWebServiceSpy).getPlayerByName(PLAYER_NAME);
+
+        //when
+        Player player = objectUnderTest.getPlayerByName(PLAYER_NAME);
+
+        //then
+        assertThat(player, is(referencePlayer));
+        verify(playerWebServiceSpy).getWebServiceName();
+        assertThat(playerWebServiceSpy.getWebServiceName(), is(PlayerWebServiceImpl.WEB_SERVICE_NAME));
+    }
+
+
+}

File Unit Testing/Mockito - Injecting Test Doubles in Spring/src/test/resources/testApplicationContext.xml

+<?xml version="1.0" encoding="UTF-8"?>
+<beans xmlns="http://www.springframework.org/schema/beans"
+       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
+       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">
+
+    <import resource="applicationContext.xml"/>
+    <bean class="com.blogspot.postprocessor.PlayerWebServicePostProcessor" />
+</beans>