Skip to content

Commit

Permalink
Browse files Browse the repository at this point in the history
Test coverage: improve some refactorings
  • Loading branch information
garcia-jj committed Aug 29, 2012
1 parent ff1c064 commit e5ac551
Show file tree
Hide file tree
Showing 9 changed files with 155 additions and 53 deletions.
Expand Up @@ -103,7 +103,7 @@ private Class<? extends ContainerProvider> getProviderType() {
"lib/containers/<container> jars on your classpath, where <container> is your preferred container.");
}

private boolean classExists(String className) {
protected boolean classExists(String className) {
try {
Class.forName(className);
return true;
Expand Down
Expand Up @@ -16,29 +16,42 @@
*/
package br.com.caelum.vraptor.config;

import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.is;
import static org.hamcrest.Matchers.startsWith;
import static org.hamcrest.Matchers.typeCompatibleWith;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.fail;
import static org.mockito.Matchers.anyString;
import static org.mockito.Mockito.doReturn;
import static org.mockito.Mockito.spy;
import static org.mockito.Mockito.when;

import java.io.IOException;

import javax.servlet.ServletContext;
import javax.servlet.ServletException;

import org.hamcrest.MatcherAssert;
import org.hamcrest.Matchers;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import org.mockito.Mock;
import org.mockito.MockitoAnnotations;
import org.picocontainer.PicoContainer;
import org.springframework.context.ApplicationContext;

import br.com.caelum.vraptor.core.Execution;
import br.com.caelum.vraptor.core.RequestInfo;
import br.com.caelum.vraptor.ioc.Container;
import br.com.caelum.vraptor.ioc.ContainerProvider;
import br.com.caelum.vraptor.ioc.guice.GuiceProvider;
import br.com.caelum.vraptor.ioc.pico.PicoProvider;
import br.com.caelum.vraptor.ioc.spring.MissingConfigurationException;
import br.com.caelum.vraptor.ioc.spring.SpringProvider;

import com.google.inject.Guice;

public class BasicConfigurationTest {

@Mock private ServletContext context;
Expand All @@ -47,61 +60,132 @@ public class BasicConfigurationTest {
@Before
public void config() {
MockitoAnnotations.initMocks(this);
this.config = new BasicConfiguration(context);
config = new BasicConfiguration(context);
}


@Test
public void shouldReadRootDirectoryAsWebinfClasses() throws ServletException {
when(context.getRealPath("/WEB-INF/classes/")).thenReturn("/x/WEB-INF/classes/");

MatcherAssert.assertThat(config.getWebinfClassesDirectory(), is("/x/WEB-INF/classes/"));
assertThat(config.getWebinfClassesDirectory(), is("/x/WEB-INF/classes/"));
}


@Test
public void shouldUseSpringContainerAsDefaultProvider() throws ServletException {
when(context.getInitParameter(BasicConfiguration.CONTAINER_PROVIDER)).thenReturn(null);

MatcherAssert.assertThat(config.getProvider().getClass(), is(typeCompatibleWith(SpringProvider.class)));
assertThat(config.getProvider().getClass(), is(typeCompatibleWith(SpringProvider.class)));
}

@Test
public void shouldUseGuiceAs1stAlternative() throws ServletException {
BasicConfiguration configSpy = spy(config);

when(context.getInitParameter(BasicConfiguration.CONTAINER_PROVIDER)).thenReturn(null);
doReturn(false).when(configSpy).classExists(ApplicationContext.class.getName());
doReturn(true).when(configSpy).classExists(Guice.class.getName());

assertThat(configSpy.getProvider().getClass(), is(typeCompatibleWith(GuiceProvider.class)));
}

@Test
public void shouldUsePicoAs2ndAlternative() throws ServletException {
BasicConfiguration configSpy = spy(config);

when(context.getInitParameter(BasicConfiguration.CONTAINER_PROVIDER)).thenReturn(null);
doReturn(false).when(configSpy).classExists(ApplicationContext.class.getName());
doReturn(false).when(configSpy).classExists(Guice.class.getName());
doReturn(true).when(configSpy).classExists(PicoContainer.class.getName());

assertThat(configSpy.getProvider().getClass(), is(typeCompatibleWith(PicoProvider.class)));
}

@Test
public void shouldThrowExceptionWhenProviderClassWasNotFound() throws ServletException {
when(context.getInitParameter(BasicConfiguration.CONTAINER_PROVIDER)).thenReturn("UnknowClass");

try {
config.getProvider();
fail();
} catch (IllegalArgumentException e) {
assertThat(e.getMessage(), startsWith("You must configure"));
}
}

@Test
public void shouldThrowIllegalArgumentExceptionWhenProvidersWasNotFound() throws Exception {
BasicConfiguration configSpy = spy(config);

when(context.getInitParameter(BasicConfiguration.CONTAINER_PROVIDER)).thenReturn(null);
doReturn(false).when(configSpy).classExists(anyString());

try {
configSpy.getProvider();
fail();
} catch (IllegalArgumentException e) {
assertThat(e.getMessage(), startsWith("You don't have any DI container jars on your classpath."));
}
}

@Test
public void shouldReturnThatHasNoBasePackageWhenInitParamNull() throws ServletException {
when(context.getInitParameter(BasicConfiguration.BASE_PACKAGES_PARAMETER_NAME)).thenReturn(null);

MatcherAssert.assertThat(config.hasBasePackages(), is(false));
assertThat(config.hasBasePackages(), is(false));
}


@Test(expected = MissingConfigurationException.class)
public void shouldThrowMissingConfigurationExceptionIfHasNoBasePackages() {
when(context.getInitParameter(BasicConfiguration.CONTAINER_PROVIDER)).thenReturn(null);
config.getBasePackages();
}

@Test
public void testIfClasspathScanningIsEnabled() {
when(context.getInitParameter(BasicConfiguration.SCANNING_PARAM)).thenReturn(null, "disabled");

assertThat(config.isClasspathScanningEnabled(), is(true));
assertThat(config.isClasspathScanningEnabled(), is(false));
}

@Test
public void testIfHasBasePackages() {
when(context.getInitParameter(BasicConfiguration.BASE_PACKAGES_PARAMETER_NAME)).thenReturn(null, "foo.bar");

assertThat(config.hasBasePackages(), is(false));
assertThat(config.hasBasePackages(), is(true));
}

@Test
public void shouldReturnBasePackagesWhenInitParamNotNull() throws ServletException {
when(context.getInitParameter(BasicConfiguration.BASE_PACKAGES_PARAMETER_NAME)).thenReturn("some.packages");

MatcherAssert.assertThat(config.getBasePackages(), is(new String[] {"some.packages"}));
assertThat(config.getBasePackages(), is(new String[] {"some.packages"}));
}

@Test
public void shouldReturnBasePackagesArrayWhenInitParamNotNullAndHasComas() throws ServletException {
when(context.getInitParameter(BasicConfiguration.BASE_PACKAGES_PARAMETER_NAME)).thenReturn("some.packages,other.packages");

MatcherAssert.assertThat(config.getBasePackages(), is(new String[] {"some.packages", "other.packages"}));
assertThat(config.getBasePackages(), is(new String[] {"some.packages", "other.packages"}));
}

@Test
public void shouldReturnBasePackagesArrayWhenInitParamNotNullAndHasComasAndSpaces() throws ServletException {
when(context.getInitParameter(BasicConfiguration.BASE_PACKAGES_PARAMETER_NAME)).thenReturn("some.packages, \n other.packages");

MatcherAssert.assertThat(config.getBasePackages(), is(new String[] {"some.packages", "other.packages"}));
assertThat(config.getBasePackages(), is(new String[] {"some.packages", "other.packages"}));
}

@Test
public void shouldReturnBasePackagesArrayWhenInitParamHasLeadingAndTrailingSpaces() throws ServletException {
when(context.getInitParameter(BasicConfiguration.BASE_PACKAGES_PARAMETER_NAME)).thenReturn(" \nsome.package\n ");

MatcherAssert.assertThat(config.getBasePackages(), is(new String[] {"some.package"}));
assertThat(config.getBasePackages(), is(new String[] {"some.package"}));
}



public static class MyCustomProvider implements ContainerProvider {
public void start(ServletContext context) {
}
Expand All @@ -122,7 +206,7 @@ public void shouldAllowProviderOverriding() throws ServletException {
when(context.getInitParameter(BasicConfiguration.CONTAINER_PROVIDER))
.thenReturn(MyCustomProvider.class.getName());

MatcherAssert.assertThat(config.getProvider().getClass(), Matchers.is(Matchers
assertThat(config.getProvider().getClass(), Matchers.is(Matchers
.typeCompatibleWith(MyCustomProvider.class)));
}

Expand Down Expand Up @@ -152,10 +236,10 @@ public void shouldThrowInstantiationExceptionCauseIfThereIsSuchException() {
.thenReturn(DogProvider.class.getName());
try {
config.getProvider();
Assert.fail();
fail();
} catch (ServletException e) {
Assert.assertNotNull("Should have a cause", e.getRootCause());
Assert.assertEquals(IOException.class, e.getRootCause().getClass());
assertNotNull("Should have a cause", e.getRootCause());
assertEquals(IOException.class, e.getRootCause().getClass());
}
}
}
Expand Up @@ -155,14 +155,11 @@ public void willSetOnlyNonNullParameters() throws Exception {
}

@Test(expected = InterceptionException.class)
public void shouldThrowsInterceptionExceptionIfAndIOExceptionOccurs() throws Exception {
public void shouldThrowInterceptionExceptionIfAnIOExceptionOccurs() throws Exception {
when(request.getInputStream()).thenThrow(new IOException());
when(request.getContentType()).thenReturn("application/xml");

final Deserializer deserializer = mock(Deserializer.class);
methodInfo.setParameters(new Object[] {"original1", "original2"});
when(deserializer.deserialize(null, consumeXml)).thenReturn(new Object[] {null, "deserialized"});

when(deserializers.deserializerFor("application/xml", container)).thenReturn(deserializer);
interceptor.intercept(stack, consumeXml, null);
}
Expand Down
Expand Up @@ -18,6 +18,8 @@
package br.com.caelum.vraptor.interceptor;

import static org.hamcrest.Matchers.is;
import static org.hamcrest.Matchers.not;
import static org.junit.Assert.assertThat;
import static org.junit.Assert.fail;
import static org.mockito.Matchers.any;
import static org.mockito.Matchers.argThat;
Expand All @@ -33,13 +35,12 @@
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.lang.reflect.Method;
import java.util.Arrays;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;

import junit.framework.Assert;

import org.hamcrest.Description;
import org.hamcrest.Matcher;
import org.hamcrest.TypeSafeMatcher;
Expand Down Expand Up @@ -148,7 +149,7 @@ public void whenResultIsNullAndResultWasNotUsedShouldThrowNPE() throws Exception
}

@Test
public void shouldThrowsInterceptionExceptionIfIOExceptionOccurs() throws Exception {
public void shouldThrowInterceptionExceptionIfIOExceptionOccurs() throws Exception {
Download download = mock(Download.class);

when(info.getResult()).thenReturn(download);
Expand All @@ -165,40 +166,56 @@ public void shouldThrowsInterceptionExceptionIfIOExceptionOccurs() throws Except

@Test
public void shouldNotAcceptStringReturn() throws Exception {
ResourceMethod method = DefaultResourceMethod.instanceFor(FakeResource.class, FakeResource.class.getMethod("string"));
Assert.assertFalse(new DownloadInterceptor(null, null, null).accepts(method));
Method method = FakeResource.class.getMethod("string");
assertThat(interceptor, not(accepts(method)));
}

@Test
public void shouldAcceptFile() throws Exception {
ResourceMethod method = DefaultResourceMethod.instanceFor(FakeResource.class, FakeResource.class.getMethod("file"));
Assert.assertTrue(new DownloadInterceptor(null, null, null).accepts(method));
Method method = FakeResource.class.getMethod("file");
assertThat(interceptor, accepts(method));
}

@Test
public void shouldAcceptInput() throws Exception {
ResourceMethod method = DefaultResourceMethod.instanceFor(FakeResource.class, FakeResource.class.getMethod("input"));
Assert.assertTrue(new DownloadInterceptor(null, null, null).accepts(method));
Method method = FakeResource.class.getMethod("input");
assertThat(interceptor, accepts(method));
}

@Test
public void shouldAcceptDownload() throws Exception {
ResourceMethod method = DefaultResourceMethod.instanceFor(FakeResource.class, FakeResource.class.getMethod("download"));
Assert.assertTrue(new DownloadInterceptor(null, null, null).accepts(method));
Method method = FakeResource.class.getMethod("download");
assertThat(interceptor, accepts(method));
}

@Test
public void shouldAcceptByte() throws Exception {
ResourceMethod method = DefaultResourceMethod.instanceFor(FakeResource.class, FakeResource.class.getMethod("asByte"));
Assert.assertTrue(new DownloadInterceptor(null, null, null).accepts(method));
Method method = FakeResource.class.getMethod("asByte");
assertThat(interceptor, accepts(method));
}

private Matcher<Interceptor> accepts(final Method method) {
return new TypeSafeMatcher<Interceptor>() {

public void describeTo(Description description) {
description.appendText("the method ").appendValue(method);
}

protected boolean matchesSafely(Interceptor item) {
ResourceMethod m = DefaultResourceMethod.instanceFor(method.getDeclaringClass(), method);
return interceptor.accepts(m);
}

protected void describeMismatchSafely(Interceptor item, Description mismatchDescription) {
}
};
}

private Matcher<byte[]> arrayStartingWith(final byte[] array) {
return new TypeSafeMatcher<byte[]>() {
@Override
protected void describeMismatchSafely(byte[] item, Description mismatchDescription) {
}
@Override

protected boolean matchesSafely(byte[] item) {
if (item.length < array.length) {
return false;
Expand Down
Expand Up @@ -6,7 +6,9 @@
import static org.hamcrest.Matchers.equalTo;
import static org.junit.Assert.assertEquals;
import static org.mockito.Matchers.any;
import static org.mockito.Matchers.anyString;
import static org.mockito.Matchers.eq;
import static org.mockito.Mockito.doAnswer;
import static org.mockito.Mockito.doThrow;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.spy;
Expand All @@ -29,7 +31,6 @@
import org.junit.Before;
import org.junit.Test;
import org.mockito.Mock;
import org.mockito.Mockito;
import org.mockito.MockitoAnnotations;
import org.mockito.invocation.InvocationOnMock;
import org.mockito.stubbing.Answer;
Expand Down Expand Up @@ -67,7 +68,7 @@ public void setup() {

mockCreator = mock(ServletFileUploadCreator.class);
mockUpload = mock(ServletFileUpload.class);
when(mockCreator.create(Mockito.any(FileItemFactory.class))).thenReturn(mockUpload);
when(mockCreator.create(any(FileItemFactory.class))).thenReturn(mockUpload);
}

@Test
Expand Down Expand Up @@ -248,8 +249,8 @@ public void shouldValidateWhenSizeLimitExceededExceptionOccurs() throws Exceptio

@Test
public void shouldCreateDirInsideAppIfTempDirAreNotAvailable() throws Exception {
DefaultMultipartConfig configSpy = (DefaultMultipartConfig) Mockito.spy(config);
Mockito.doThrow(new IOException()).when(configSpy).createTempFile();
DefaultMultipartConfig configSpy = (DefaultMultipartConfig) spy(config);
doThrow(new IOException()).when(configSpy).createTempFile();

interceptor = new CommonsUploadMultipartInterceptor(request, parameters, configSpy, validator, mockCreator);

Expand Down Expand Up @@ -277,14 +278,15 @@ public void checkUploadedFile() throws Exception {
when(request.getContentType()).thenReturn("multipart/form-data");
when(request.getMethod()).thenReturn("POST");

Mockito.doAnswer(new Answer<Object>() {
Answer<Object> answer = new Answer<Object>() {
public Object answer(InvocationOnMock invocation) throws Throwable {
Object[] args = invocation.getArguments();
attributes.put((String) args[0], args[1]);
return null;
}
}).when(request).setAttribute(Mockito.anyString(), Mockito.anyString());

};

doAnswer(answer).when(request).setAttribute(anyString(), anyString());
when(mockUpload.parseRequest(request)).thenReturn(elements);

interceptor.intercept(stack, method, instance);
Expand Down

0 comments on commit e5ac551

Please sign in to comment.