DATACMNS-266 - Use new common Maven build infrastructure.
Simplified project setup to be a single module build again. Using Spring Data Build parent POM to simplify project setup. See https://github.com/SpringSource/spring-data-build#spring-data-build-infrastructure
This commit is contained in:
@@ -0,0 +1,30 @@
|
||||
package org.springframework.data.auditing;
|
||||
|
||||
import java.util.Date;
|
||||
|
||||
import org.joda.time.DateTime;
|
||||
import org.springframework.data.annotation.CreatedBy;
|
||||
import org.springframework.data.annotation.CreatedDate;
|
||||
import org.springframework.data.annotation.LastModifiedBy;
|
||||
import org.springframework.data.annotation.LastModifiedDate;
|
||||
|
||||
/**
|
||||
* Sample entity using annotation based auditing.
|
||||
*
|
||||
* @author Oliver Gierke
|
||||
* @since 1.5
|
||||
*/
|
||||
class AnnotatedUser {
|
||||
|
||||
@CreatedBy
|
||||
Object createdBy;
|
||||
|
||||
@CreatedDate
|
||||
DateTime createdDate;
|
||||
|
||||
@LastModifiedBy
|
||||
Object lastModifiedBy;
|
||||
|
||||
@LastModifiedDate
|
||||
Date lastModifiedDate;
|
||||
}
|
||||
@@ -0,0 +1,100 @@
|
||||
/*
|
||||
* Copyright 2012 the original author or authors.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
package org.springframework.data.auditing;
|
||||
|
||||
import static org.hamcrest.CoreMatchers.*;
|
||||
import static org.junit.Assert.*;
|
||||
|
||||
import java.lang.reflect.Field;
|
||||
|
||||
import org.junit.Rule;
|
||||
import org.junit.Test;
|
||||
import org.junit.rules.ExpectedException;
|
||||
import org.springframework.data.annotation.CreatedDate;
|
||||
import org.springframework.util.ReflectionUtils;
|
||||
|
||||
/**
|
||||
* Unit test for {@link org.springframework.data.auditing.AnnotationAuditingMetadata}.
|
||||
*
|
||||
* @author Ranie Jade Ramiso
|
||||
* @author Oliver Gierke
|
||||
* @since 1.5
|
||||
*/
|
||||
public class AnnotationAuditingMetadataUnitTests {
|
||||
|
||||
static final Field createdByField = ReflectionUtils.findField(AnnotatedUser.class, "createdBy");
|
||||
static final Field createdDateField = ReflectionUtils.findField(AnnotatedUser.class, "createdDate");
|
||||
static final Field lastModifiedByField = ReflectionUtils.findField(AnnotatedUser.class, "lastModifiedBy");
|
||||
static final Field lastModifiedDateField = ReflectionUtils.findField(AnnotatedUser.class, "lastModifiedDate");
|
||||
|
||||
@Rule
|
||||
public ExpectedException exception = ExpectedException.none();
|
||||
|
||||
@Test
|
||||
public void checkAnnotationDiscovery() {
|
||||
|
||||
AnnotationAuditingMetadata metadata = AnnotationAuditingMetadata.getMetadata(AnnotatedUser.class);
|
||||
assertThat(metadata, is(notNullValue()));
|
||||
|
||||
assertThat(createdByField, is(metadata.getCreatedByField()));
|
||||
assertThat(createdDateField, is(metadata.getCreatedDateField()));
|
||||
assertThat(lastModifiedByField, is(metadata.getLastModifiedByField()));
|
||||
assertThat(lastModifiedDateField, is(metadata.getLastModifiedDateField()));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void checkCaching() {
|
||||
|
||||
AnnotationAuditingMetadata firstCall = AnnotationAuditingMetadata.getMetadata(AnnotatedUser.class);
|
||||
assertThat(firstCall, is(notNullValue()));
|
||||
|
||||
AnnotationAuditingMetadata secondCall = AnnotationAuditingMetadata.getMetadata(AnnotatedUser.class);
|
||||
assertThat(firstCall, is(secondCall));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void checkIsAuditable() {
|
||||
|
||||
AnnotationAuditingMetadata metadata = AnnotationAuditingMetadata.getMetadata(AnnotatedUser.class);
|
||||
assertThat(metadata, is(notNullValue()));
|
||||
;
|
||||
assertThat(metadata.isAuditable(), is(true));
|
||||
|
||||
metadata = AnnotationAuditingMetadata.getMetadata(NonAuditableUser.class);
|
||||
assertThat(metadata, is(notNullValue()));
|
||||
assertThat(metadata.isAuditable(), is(false));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void rejectsInvalidDateTypeField() {
|
||||
|
||||
class Sample {
|
||||
@CreatedDate
|
||||
String field;
|
||||
}
|
||||
|
||||
exception.expect(IllegalStateException.class);
|
||||
exception.expectMessage(String.class.getName());
|
||||
exception.expectMessage("field");
|
||||
|
||||
AnnotationAuditingMetadata.getMetadata(Sample.class);
|
||||
}
|
||||
|
||||
@SuppressWarnings("unused")
|
||||
static class NonAuditableUser {
|
||||
private Object nonAuditProperty;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,58 @@
|
||||
/*
|
||||
* Copyright 2012 the original author or authors.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
package org.springframework.data.auditing;
|
||||
|
||||
import static org.hamcrest.CoreMatchers.*;
|
||||
import static org.junit.Assert.*;
|
||||
|
||||
import org.junit.Test;
|
||||
import org.springframework.data.auditing.AuditableBeanWrapperFactory.AuditableInterfaceBeanWrapper;
|
||||
import org.springframework.data.auditing.AuditableBeanWrapperFactory.ReflectionAuditingBeanWrapper;
|
||||
|
||||
/**
|
||||
* @author Oliver Gierke
|
||||
* @since 1.5
|
||||
*/
|
||||
public class AuditableBeanWrapperFactoryUnitTests {
|
||||
|
||||
AuditableBeanWrapperFactory factory = new AuditableBeanWrapperFactory();
|
||||
|
||||
@Test
|
||||
public void returnsNullForNullSource() {
|
||||
assertThat(factory.getBeanWrapperFor(null), is(nullValue()));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void returnsAuditableInterfaceBeanWrapperForAuditable() {
|
||||
|
||||
AuditableBeanWrapper wrapper = factory.getBeanWrapperFor(new AuditedUser());
|
||||
assertThat(wrapper, is(instanceOf(AuditableInterfaceBeanWrapper.class)));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void returnsReflectionAuditingBeanWrapperForNonAuditableButAnnotated() {
|
||||
|
||||
AuditableBeanWrapper wrapper = factory.getBeanWrapperFor(new AnnotatedUser());
|
||||
assertThat(wrapper, is(instanceOf(ReflectionAuditingBeanWrapper.class)));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void returnsNullForNonAuditableType() {
|
||||
|
||||
AuditableBeanWrapper wrapper = factory.getBeanWrapperFor(new Object());
|
||||
assertThat(wrapper, is(nullValue()));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,76 @@
|
||||
/*
|
||||
* Copyright 2012 the original author or authors.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
package org.springframework.data.auditing;
|
||||
|
||||
import org.joda.time.DateTime;
|
||||
import org.springframework.data.domain.Auditable;
|
||||
|
||||
/**
|
||||
* Sample implementation of {@link Auditable}.
|
||||
*
|
||||
* @author Oliver Gierke
|
||||
* @since 1.5
|
||||
*/
|
||||
class AuditedUser implements Auditable<AuditedUser, Long> {
|
||||
|
||||
private static final long serialVersionUID = -840865084027597951L;
|
||||
|
||||
Long id;
|
||||
AuditedUser createdBy;
|
||||
AuditedUser modifiedBy;
|
||||
DateTime createdDate;
|
||||
DateTime modifiedDate;
|
||||
|
||||
public Long getId() {
|
||||
return id;
|
||||
}
|
||||
|
||||
public boolean isNew() {
|
||||
return id == null;
|
||||
}
|
||||
|
||||
public AuditedUser getCreatedBy() {
|
||||
return createdBy;
|
||||
}
|
||||
|
||||
public void setCreatedBy(AuditedUser createdBy) {
|
||||
this.createdBy = createdBy;
|
||||
}
|
||||
|
||||
public DateTime getCreatedDate() {
|
||||
return createdDate;
|
||||
}
|
||||
|
||||
public void setCreatedDate(DateTime creationDate) {
|
||||
this.createdDate = creationDate;
|
||||
}
|
||||
|
||||
public AuditedUser getLastModifiedBy() {
|
||||
return modifiedBy;
|
||||
}
|
||||
|
||||
public void setLastModifiedBy(AuditedUser lastModifiedBy) {
|
||||
this.modifiedBy = lastModifiedBy;
|
||||
}
|
||||
|
||||
public DateTime getLastModifiedDate() {
|
||||
return modifiedDate;
|
||||
}
|
||||
|
||||
public void setLastModifiedDate(DateTime lastModifiedDate) {
|
||||
this.modifiedDate = lastModifiedDate;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,154 @@
|
||||
/*
|
||||
* Copyright 2008-2012 the original author or authors.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
package org.springframework.data.auditing;
|
||||
|
||||
import static org.junit.Assert.*;
|
||||
import static org.mockito.Mockito.*;
|
||||
|
||||
import org.junit.Before;
|
||||
import org.junit.Test;
|
||||
import org.springframework.data.domain.AuditorAware;
|
||||
|
||||
/**
|
||||
* Unit test for {@code AuditingHandler}.
|
||||
*
|
||||
* @author Oliver Gierke
|
||||
* @since 1.5
|
||||
*/
|
||||
@SuppressWarnings("unchecked")
|
||||
public class AuditingHandlerUnitTests {
|
||||
|
||||
AuditingHandler<AuditedUser> handler;
|
||||
AuditorAware<AuditedUser> auditorAware;
|
||||
|
||||
AuditedUser user;
|
||||
|
||||
@Before
|
||||
public void setUp() {
|
||||
|
||||
handler = getHandler();
|
||||
user = new AuditedUser();
|
||||
|
||||
auditorAware = mock(AuditorAware.class);
|
||||
when(auditorAware.getCurrentAuditor()).thenReturn(user);
|
||||
}
|
||||
|
||||
protected AuditingHandler<AuditedUser> getHandler() {
|
||||
return new AuditingHandler<AuditedUser>();
|
||||
}
|
||||
|
||||
/**
|
||||
* Checks that the advice does not set auditor on the target entity if no {@code AuditorAware} was configured.
|
||||
*/
|
||||
@Test
|
||||
public void doesNotSetAuditorIfNotConfigured() {
|
||||
|
||||
handler.markCreated(user);
|
||||
|
||||
assertNotNull(user.getCreatedDate());
|
||||
assertNotNull(user.getLastModifiedDate());
|
||||
|
||||
assertNull(user.getCreatedBy());
|
||||
assertNull(user.getLastModifiedBy());
|
||||
}
|
||||
|
||||
/**
|
||||
* Checks that the advice sets the auditor on the target entity if an {@code AuditorAware} was configured.
|
||||
*/
|
||||
@Test
|
||||
public void setsAuditorIfConfigured() {
|
||||
|
||||
handler.setAuditorAware(auditorAware);
|
||||
|
||||
handler.markCreated(user);
|
||||
|
||||
assertNotNull(user.getCreatedDate());
|
||||
assertNotNull(user.getLastModifiedDate());
|
||||
|
||||
assertNotNull(user.getCreatedBy());
|
||||
assertNotNull(user.getLastModifiedBy());
|
||||
|
||||
verify(auditorAware).getCurrentAuditor();
|
||||
}
|
||||
|
||||
/**
|
||||
* Checks that the advice does not set modification information on creation if the falg is set to {@code false}.
|
||||
*/
|
||||
@Test
|
||||
public void honoursModifiedOnCreationFlag() {
|
||||
|
||||
handler.setAuditorAware(auditorAware);
|
||||
handler.setModifyOnCreation(false);
|
||||
handler.markCreated(user);
|
||||
|
||||
assertNotNull(user.getCreatedDate());
|
||||
assertNotNull(user.getCreatedBy());
|
||||
|
||||
assertNull(user.getLastModifiedBy());
|
||||
assertNull(user.getLastModifiedDate());
|
||||
|
||||
verify(auditorAware).getCurrentAuditor();
|
||||
}
|
||||
|
||||
/**
|
||||
* Tests that the advice only sets modification data if a not-new entity is handled.
|
||||
*/
|
||||
@Test
|
||||
public void onlySetsModificationDataOnNotNewEntities() {
|
||||
|
||||
user = new AuditedUser();
|
||||
user.id = 1L;
|
||||
|
||||
handler.setAuditorAware(auditorAware);
|
||||
handler.markModified(user);
|
||||
|
||||
assertNull(user.getCreatedBy());
|
||||
assertNull(user.getCreatedDate());
|
||||
|
||||
assertNotNull(user.getLastModifiedBy());
|
||||
assertNotNull(user.getLastModifiedDate());
|
||||
|
||||
verify(auditorAware).getCurrentAuditor();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void doesNotSetTimeIfConfigured() {
|
||||
|
||||
handler.setDateTimeForNow(false);
|
||||
handler.setAuditorAware(auditorAware);
|
||||
handler.markCreated(user);
|
||||
|
||||
assertNotNull(user.getCreatedBy());
|
||||
assertNull(user.getCreatedDate());
|
||||
|
||||
assertNotNull(user.getLastModifiedBy());
|
||||
assertNull(user.getLastModifiedDate());
|
||||
}
|
||||
|
||||
/**
|
||||
* @see DATAJPA-9
|
||||
*/
|
||||
@Test
|
||||
public void usesDateTimeProviderIfConfigured() {
|
||||
|
||||
DateTimeProvider provider = mock(DateTimeProvider.class);
|
||||
|
||||
handler.setDateTimeProvider(provider);
|
||||
handler.markCreated(user);
|
||||
|
||||
verify(provider, times(1)).getDateTime();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,76 @@
|
||||
/*
|
||||
* Copyright 2008-2012 the original author or authors.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
package org.springframework.data.auditing;
|
||||
|
||||
import static org.hamcrest.CoreMatchers.*;
|
||||
import static org.junit.Assert.*;
|
||||
import static org.mockito.Mockito.*;
|
||||
|
||||
import org.junit.Before;
|
||||
import org.junit.Test;
|
||||
import org.junit.runner.RunWith;
|
||||
import org.mockito.Mock;
|
||||
import org.mockito.Mockito;
|
||||
import org.mockito.runners.MockitoJUnitRunner;
|
||||
import org.springframework.data.support.IsNewStrategy;
|
||||
import org.springframework.data.support.IsNewStrategyFactory;
|
||||
|
||||
/**
|
||||
* Unit test for {@code AuditingHandler}.
|
||||
*
|
||||
* @author Oliver Gierke
|
||||
* @since 1.5
|
||||
*/
|
||||
@RunWith(MockitoJUnitRunner.class)
|
||||
public class IsNewAwareAuditingHandlerUnitTests extends AuditingHandlerUnitTests {
|
||||
|
||||
@Mock
|
||||
IsNewStrategyFactory factory;
|
||||
@Mock
|
||||
IsNewStrategy strategy;
|
||||
|
||||
@Before
|
||||
public void init() {
|
||||
when(factory.getIsNewStrategy(Mockito.any(Class.class))).thenReturn(strategy);
|
||||
}
|
||||
|
||||
@Override
|
||||
protected IsNewAwareAuditingHandler<AuditedUser> getHandler() {
|
||||
return new IsNewAwareAuditingHandler<AuditedUser>(factory);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void delegatesToMarkCreatedForNewEntity() {
|
||||
|
||||
when(strategy.isNew(Mockito.any(Object.class))).thenReturn(true);
|
||||
AuditedUser user = new AuditedUser();
|
||||
getHandler().markAudited(user);
|
||||
|
||||
assertThat(user.createdDate, is(notNullValue()));
|
||||
assertThat(user.modifiedDate, is(notNullValue()));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void delegatesToMarkModifiedForNonNewEntity() {
|
||||
|
||||
when(strategy.isNew(Mockito.any(Object.class))).thenReturn(false);
|
||||
AuditedUser user = new AuditedUser();
|
||||
getHandler().markAudited(user);
|
||||
|
||||
assertThat(user.createdDate, is(nullValue()));
|
||||
assertThat(user.modifiedDate, is(notNullValue()));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,96 @@
|
||||
/*
|
||||
* Copyright 2012 the original author or authors.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
package org.springframework.data.auditing;
|
||||
|
||||
import static org.hamcrest.CoreMatchers.*;
|
||||
import static org.junit.Assert.*;
|
||||
|
||||
import org.joda.time.DateTime;
|
||||
import org.junit.Before;
|
||||
import org.junit.Test;
|
||||
import org.springframework.data.annotation.CreatedDate;
|
||||
import org.springframework.data.annotation.LastModifiedDate;
|
||||
import org.springframework.data.auditing.AuditableBeanWrapperFactory.ReflectionAuditingBeanWrapper;
|
||||
|
||||
/**
|
||||
* Unit tests for {@link ReflectionAuditingBeanWrapper}.
|
||||
*
|
||||
* @author Oliver Gierke
|
||||
* @since 1.5
|
||||
*/
|
||||
public class ReflectionAuditingBeanWrapperUnitTests {
|
||||
|
||||
AnnotationAuditingMetadata metadata;
|
||||
AnnotatedUser user;
|
||||
AuditableBeanWrapper wrapper;
|
||||
|
||||
DateTime time = new DateTime();
|
||||
|
||||
@Before
|
||||
public void setUp() {
|
||||
|
||||
this.user = new AnnotatedUser();
|
||||
this.wrapper = new ReflectionAuditingBeanWrapper(user);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void setsDateTimeFieldCorrectly() {
|
||||
|
||||
wrapper.setCreatedDate(time);
|
||||
assertThat(user.createdDate, is(time));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void setsDateFieldCorrectly() {
|
||||
|
||||
wrapper.setLastModifiedDate(time);
|
||||
assertThat(user.lastModifiedDate, is(time.toDate()));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void setsLongFieldCorrectly() {
|
||||
|
||||
class Sample {
|
||||
|
||||
@CreatedDate
|
||||
Long createdDate;
|
||||
|
||||
@LastModifiedDate
|
||||
long modifiedDate;
|
||||
}
|
||||
|
||||
Sample sample = new Sample();
|
||||
AuditableBeanWrapper wrapper = new ReflectionAuditingBeanWrapper(sample);
|
||||
|
||||
wrapper.setCreatedDate(time);
|
||||
assertThat(sample.createdDate, is(time.getMillis()));
|
||||
|
||||
wrapper.setLastModifiedDate(time);
|
||||
assertThat(sample.modifiedDate, is(time.getMillis()));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void setsAuditorFieldsCorrectly() {
|
||||
|
||||
Object object = new Object();
|
||||
|
||||
wrapper.setCreatedBy(object);
|
||||
assertThat(user.createdBy, is(object));
|
||||
|
||||
wrapper.setLastModifiedBy(object);
|
||||
assertThat(user.lastModifiedBy, is(object));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,77 @@
|
||||
/*
|
||||
* Copyright 2011 by the original author(s).
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
package org.springframework.data.authentication;
|
||||
|
||||
import static org.hamcrest.CoreMatchers.*;
|
||||
import static org.junit.Assert.*;
|
||||
|
||||
import org.junit.Test;
|
||||
|
||||
/**
|
||||
* Unit tests for {@link UserCredentials}.
|
||||
*
|
||||
* @author Oliver Gierke
|
||||
*/
|
||||
public class UserCredentialsUnitTests {
|
||||
|
||||
@Test
|
||||
public void treatsEmptyStringAsNull() {
|
||||
|
||||
UserCredentials credentials = new UserCredentials("", "");
|
||||
assertThat(credentials.getUsername(), is(nullValue()));
|
||||
assertThat(credentials.hasUsername(), is(false));
|
||||
assertThat(credentials.getPassword(), is(nullValue()));
|
||||
assertThat(credentials.hasPassword(), is(false));
|
||||
}
|
||||
|
||||
/**
|
||||
* @see DATACMNS-142
|
||||
*/
|
||||
@Test
|
||||
public void noCredentialsNullsUsernameAndPassword() {
|
||||
|
||||
assertThat(UserCredentials.NO_CREDENTIALS.getUsername(), is(nullValue()));
|
||||
assertThat(UserCredentials.NO_CREDENTIALS.getPassword(), is(nullValue()));
|
||||
}
|
||||
|
||||
/**
|
||||
* @see DATACMNS-142
|
||||
*/
|
||||
@Test
|
||||
public void configuresUsernameCorrectly() {
|
||||
|
||||
UserCredentials credentials = new UserCredentials("username", null);
|
||||
|
||||
assertThat(credentials.hasUsername(), is(true));
|
||||
assertThat(credentials.getUsername(), is("username"));
|
||||
assertThat(credentials.hasPassword(), is(false));
|
||||
assertThat(credentials.getPassword(), is(nullValue()));
|
||||
}
|
||||
|
||||
/**
|
||||
* @see DATACMNS-142
|
||||
*/
|
||||
@Test
|
||||
public void configuresPasswordCorrectly() {
|
||||
|
||||
UserCredentials credentials = new UserCredentials(null, "password");
|
||||
|
||||
assertThat(credentials.hasUsername(), is(false));
|
||||
assertThat(credentials.getUsername(), is(nullValue()));
|
||||
assertThat(credentials.hasPassword(), is(true));
|
||||
assertThat(credentials.getPassword(), is("password"));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,97 @@
|
||||
/*
|
||||
* Copyright 2010-2012 the original author or authors.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
package org.springframework.data.config;
|
||||
|
||||
import static org.hamcrest.Matchers.*;
|
||||
import static org.junit.Assert.*;
|
||||
|
||||
import java.io.IOException;
|
||||
|
||||
import javax.xml.parsers.DocumentBuilderFactory;
|
||||
import javax.xml.parsers.ParserConfigurationException;
|
||||
|
||||
import org.hamcrest.Matcher;
|
||||
import org.hamcrest.Matchers;
|
||||
import org.junit.Before;
|
||||
import org.junit.Test;
|
||||
import org.junit.runner.RunWith;
|
||||
import org.mockito.Mock;
|
||||
import org.mockito.runners.MockitoJUnitRunner;
|
||||
import org.springframework.beans.factory.parsing.ReaderContext;
|
||||
import org.springframework.context.annotation.ClassPathScanningCandidateComponentProvider;
|
||||
import org.springframework.core.io.ClassPathResource;
|
||||
import org.springframework.core.io.Resource;
|
||||
import org.springframework.core.type.filter.AssignableTypeFilter;
|
||||
import org.springframework.core.type.filter.TypeFilter;
|
||||
import org.springframework.data.config.TypeFilterParser;
|
||||
import org.springframework.data.config.TypeFilterParser.Type;
|
||||
import org.springframework.util.xml.DomUtils;
|
||||
import org.w3c.dom.Element;
|
||||
import org.xml.sax.SAXException;
|
||||
|
||||
/**
|
||||
* Unit test for {@link TypeFilterParser}.
|
||||
*
|
||||
* @author Oliver Gierke
|
||||
*/
|
||||
@RunWith(MockitoJUnitRunner.class)
|
||||
public class TypeFilterParserUnitTests {
|
||||
|
||||
static final Matcher<Iterable<? super AssignableTypeFilter>> IS_ASSIGNABLE_TYPE_FILTER = hasItem(Matchers
|
||||
.isA(AssignableTypeFilter.class));
|
||||
|
||||
TypeFilterParser parser;
|
||||
Element documentElement;
|
||||
|
||||
@Mock
|
||||
ReaderContext context;
|
||||
@Mock
|
||||
ClassLoader classLoader;
|
||||
|
||||
@Mock
|
||||
ClassPathScanningCandidateComponentProvider scanner;
|
||||
|
||||
@Before
|
||||
public void setUp() throws SAXException, IOException, ParserConfigurationException {
|
||||
|
||||
parser = new TypeFilterParser(context, classLoader);
|
||||
|
||||
Resource sampleXmlFile = new ClassPathResource("type-filter-test.xml", TypeFilterParserUnitTests.class);
|
||||
|
||||
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
|
||||
factory.setNamespaceAware(true);
|
||||
|
||||
documentElement = factory.newDocumentBuilder().parse(sampleXmlFile.getInputStream()).getDocumentElement();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void parsesIncludesCorrectly() throws Exception {
|
||||
|
||||
Element element = DomUtils.getChildElementByTagName(documentElement, "firstSample");
|
||||
|
||||
Iterable<TypeFilter> filters = parser.parseTypeFilters(element, Type.INCLUDE);
|
||||
assertThat(filters, IS_ASSIGNABLE_TYPE_FILTER);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void parsesExcludesCorrectly() throws Exception {
|
||||
|
||||
Element element = DomUtils.getChildElementByTagName(documentElement, "secondSample");
|
||||
|
||||
Iterable<TypeFilter> filters = parser.parseTypeFilters(element, Type.EXCLUDE);
|
||||
assertThat(filters, IS_ASSIGNABLE_TYPE_FILTER);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,77 @@
|
||||
/*
|
||||
* Copyright 2011-2012 the original author or authors.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
package org.springframework.data.convert;
|
||||
|
||||
import static org.hamcrest.Matchers.*;
|
||||
import static org.junit.Assert.*;
|
||||
|
||||
import java.util.Collections;
|
||||
import java.util.HashMap;
|
||||
import java.util.Map;
|
||||
|
||||
import org.junit.Before;
|
||||
import org.junit.Test;
|
||||
import org.junit.runner.RunWith;
|
||||
import org.mockito.runners.MockitoJUnitRunner;
|
||||
import org.springframework.data.mapping.PersistentProperty;
|
||||
import org.springframework.data.util.ClassTypeInformation;
|
||||
import org.springframework.data.util.TypeInformation;
|
||||
|
||||
/**
|
||||
* Unit tests for {@link ConfigurableTypeMapper}.
|
||||
*
|
||||
* @author Oliver Gierke
|
||||
*/
|
||||
@RunWith(MockitoJUnitRunner.class)
|
||||
public class ConfigurableTypeInformationMapperUnitTests<T extends PersistentProperty<T>> {
|
||||
|
||||
ConfigurableTypeInformationMapper mapper;
|
||||
|
||||
@Before
|
||||
public void setUp() {
|
||||
mapper = new ConfigurableTypeInformationMapper(Collections.singletonMap(String.class, "1"));
|
||||
}
|
||||
|
||||
@Test(expected = IllegalArgumentException.class)
|
||||
public void rejectsNullTypeMap() {
|
||||
new ConfigurableTypeInformationMapper(null);
|
||||
}
|
||||
|
||||
@Test(expected = IllegalArgumentException.class)
|
||||
public void rejectsNonBijectionalMap() {
|
||||
|
||||
Map<Class<?>, String> map = new HashMap<Class<?>, String>();
|
||||
map.put(String.class, "1");
|
||||
map.put(Object.class, "1");
|
||||
|
||||
new ConfigurableTypeInformationMapper(map);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void writesMapKeyForType() {
|
||||
|
||||
assertThat(mapper.createAliasFor(ClassTypeInformation.from(String.class)), is((Object) "1"));
|
||||
assertThat(mapper.createAliasFor(ClassTypeInformation.from(Object.class)), is(nullValue()));
|
||||
}
|
||||
|
||||
@Test
|
||||
@SuppressWarnings("rawtypes")
|
||||
public void readsTypeForMapKey() {
|
||||
|
||||
assertThat(mapper.resolveTypeFrom("1"), is((TypeInformation) ClassTypeInformation.from(String.class)));
|
||||
assertThat(mapper.resolveTypeFrom("unmapped"), is(nullValue()));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,87 @@
|
||||
/*
|
||||
* Copyright 2012 the original author or authors.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
package org.springframework.data.convert;
|
||||
|
||||
import static org.mockito.Mockito.*;
|
||||
import static org.junit.Assert.*;
|
||||
import static org.hamcrest.CoreMatchers.*;
|
||||
|
||||
import java.util.Collections;
|
||||
import java.util.Map;
|
||||
|
||||
import org.junit.Test;
|
||||
import org.junit.runner.RunWith;
|
||||
import org.mockito.Mock;
|
||||
import org.mockito.runners.MockitoJUnitRunner;
|
||||
import org.springframework.data.mapping.PersistentEntity;
|
||||
|
||||
/**
|
||||
* Unit tests for {@link EntityInstantiators}.
|
||||
*
|
||||
* @author Oliver Gierke
|
||||
*/
|
||||
@RunWith(MockitoJUnitRunner.class)
|
||||
public class EntityInstantiatorsUnitTests {
|
||||
|
||||
@Mock
|
||||
PersistentEntity<?, ?> entity;
|
||||
|
||||
@Mock
|
||||
EntityInstantiator customInstantiator;
|
||||
|
||||
@Test(expected = IllegalArgumentException.class)
|
||||
public void rejectsNullFallbackInstantiator() {
|
||||
new EntityInstantiators((EntityInstantiator) null);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void usesReflectionEntityInstantiatorAsDefaultFallback() {
|
||||
|
||||
EntityInstantiators instantiators = new EntityInstantiators();
|
||||
assertThat(instantiators.getInstantiatorFor(entity), is((EntityInstantiator) ReflectionEntityInstantiator.INSTANCE));
|
||||
}
|
||||
|
||||
@Test
|
||||
@SuppressWarnings({ "unchecked", "rawtypes" })
|
||||
public void returnsCustomInstantiatorForTypeIfRegistered() {
|
||||
|
||||
when(entity.getType()).thenReturn((Class) String.class);
|
||||
|
||||
Map<Class<?>, EntityInstantiator> customInstantiators = Collections.<Class<?>, EntityInstantiator> singletonMap(
|
||||
String.class, customInstantiator);
|
||||
|
||||
EntityInstantiators instantiators = new EntityInstantiators(customInstantiators);
|
||||
assertThat(instantiators.getInstantiatorFor(entity), is(customInstantiator));
|
||||
}
|
||||
|
||||
@Test
|
||||
@SuppressWarnings({ "unchecked", "rawtypes" })
|
||||
public void usesCustomFallbackInstantiatorsIfConfigured() {
|
||||
|
||||
when(entity.getType()).thenReturn((Class) Object.class);
|
||||
|
||||
Map<Class<?>, EntityInstantiator> customInstantiators = Collections.<Class<?>, EntityInstantiator> singletonMap(
|
||||
String.class, ReflectionEntityInstantiator.INSTANCE);
|
||||
|
||||
EntityInstantiators instantiators = new EntityInstantiators(customInstantiator, customInstantiators);
|
||||
instantiators.getInstantiatorFor(entity);
|
||||
|
||||
assertThat(instantiators.getInstantiatorFor(entity), is(customInstantiator));
|
||||
|
||||
when(entity.getType()).thenReturn((Class) String.class);
|
||||
assertThat(instantiators.getInstantiatorFor(entity), is((EntityInstantiator) ReflectionEntityInstantiator.INSTANCE));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,106 @@
|
||||
/*
|
||||
* Copyright 2012 the original author or authors.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
package org.springframework.data.convert;
|
||||
|
||||
import static org.hamcrest.Matchers.*;
|
||||
import static org.junit.Assert.*;
|
||||
import static org.springframework.data.util.ClassTypeInformation.*;
|
||||
|
||||
import java.util.Collections;
|
||||
|
||||
import org.junit.Before;
|
||||
import org.junit.Test;
|
||||
import org.springframework.data.annotation.TypeAlias;
|
||||
import org.springframework.data.mapping.MappingMetadataTests;
|
||||
import org.springframework.data.mapping.MappingMetadataTests.SampleMappingContext;
|
||||
import org.springframework.data.mapping.MappingMetadataTests.SampleProperty;
|
||||
import org.springframework.data.mapping.PersistentEntity;
|
||||
import org.springframework.data.util.ClassTypeInformation;
|
||||
import org.springframework.data.util.TypeInformation;
|
||||
|
||||
/**
|
||||
* Unit tests for {@link MappingContextTypeInformationMapper}.
|
||||
*
|
||||
* @author Oliver Gierke
|
||||
*/
|
||||
public class MappingContextTypeInformationMapperUnitTests {
|
||||
|
||||
SampleMappingContext mappingContext;
|
||||
TypeInformationMapper mapper;
|
||||
|
||||
@Before
|
||||
public void setUp() {
|
||||
mappingContext = new MappingMetadataTests.SampleMappingContext();
|
||||
}
|
||||
|
||||
@Test(expected = IllegalArgumentException.class)
|
||||
public void rejectsNullMappingContext() {
|
||||
new MappingContextTypeInformationMapper(null);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void extractsAliasInfoFromMappingContext() {
|
||||
|
||||
mappingContext.setInitialEntitySet(Collections.singleton(Entity.class));
|
||||
mappingContext.initialize();
|
||||
|
||||
mapper = new MappingContextTypeInformationMapper(mappingContext);
|
||||
|
||||
assertThat(mapper.createAliasFor(ClassTypeInformation.from(Entity.class)), is((Object) "foo"));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void extractsAliasForUnknownType() {
|
||||
|
||||
SampleMappingContext mappingContext = new MappingMetadataTests.SampleMappingContext();
|
||||
mappingContext.initialize();
|
||||
|
||||
mapper = new MappingContextTypeInformationMapper(mappingContext);
|
||||
|
||||
assertThat(mapper.createAliasFor(from(Entity.class)), is((Object) "foo"));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void doesNotReturnTypeAliasForSimpleType() {
|
||||
|
||||
SampleMappingContext mappingContext = new MappingMetadataTests.SampleMappingContext();
|
||||
mappingContext.initialize();
|
||||
|
||||
mapper = new MappingContextTypeInformationMapper(mappingContext);
|
||||
assertThat(mapper.createAliasFor(from(String.class)), is(nullValue()));
|
||||
}
|
||||
|
||||
@Test
|
||||
@SuppressWarnings("rawtypes")
|
||||
public void detectsTypeForUnknownEntity() {
|
||||
|
||||
SampleMappingContext mappingContext = new MappingMetadataTests.SampleMappingContext();
|
||||
mappingContext.initialize();
|
||||
|
||||
mapper = new MappingContextTypeInformationMapper(mappingContext);
|
||||
assertThat(mapper.resolveTypeFrom("foo"), is(nullValue()));
|
||||
|
||||
PersistentEntity<?, SampleProperty> entity = mappingContext.getPersistentEntity(Entity.class);
|
||||
|
||||
assertThat(entity, is(notNullValue()));
|
||||
assertThat(mapper.resolveTypeFrom("foo"), is((TypeInformation) from(Entity.class)));
|
||||
}
|
||||
|
||||
@TypeAlias("foo")
|
||||
static class Entity {
|
||||
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,130 @@
|
||||
/*
|
||||
* Copyright 2012 the original author or authors.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
package org.springframework.data.convert;
|
||||
|
||||
import static org.hamcrest.Matchers.*;
|
||||
import static org.junit.Assert.*;
|
||||
import static org.mockito.Mockito.*;
|
||||
import static org.springframework.data.convert.ReflectionEntityInstantiator.*;
|
||||
|
||||
import java.lang.reflect.Field;
|
||||
|
||||
import org.junit.Test;
|
||||
import org.junit.runner.RunWith;
|
||||
import org.mockito.Mock;
|
||||
import org.mockito.runners.MockitoJUnitRunner;
|
||||
import org.springframework.data.convert.ReflectionEntityInstantiatorUnitTests.Outer.Inner;
|
||||
import org.springframework.data.mapping.PersistentEntity;
|
||||
import org.springframework.data.mapping.PersistentProperty;
|
||||
import org.springframework.data.mapping.PreferredConstructor;
|
||||
import org.springframework.data.mapping.PreferredConstructor.Parameter;
|
||||
import org.springframework.data.mapping.model.BasicPersistentEntity;
|
||||
import org.springframework.data.mapping.model.ParameterValueProvider;
|
||||
import org.springframework.data.mapping.model.PreferredConstructorDiscoverer;
|
||||
import org.springframework.data.util.ClassTypeInformation;
|
||||
import org.springframework.util.ReflectionUtils;
|
||||
import org.springframework.util.ReflectionUtils.FieldCallback;
|
||||
|
||||
/**
|
||||
* Unit tests for {@link ReflectionEntityInstantiator}.
|
||||
*
|
||||
* @author Oliver Gierke
|
||||
*/
|
||||
@RunWith(MockitoJUnitRunner.class)
|
||||
public class ReflectionEntityInstantiatorUnitTests<P extends PersistentProperty<P>> {
|
||||
|
||||
@Mock
|
||||
PersistentEntity<?, P> entity;
|
||||
@Mock
|
||||
ParameterValueProvider<P> provider;
|
||||
@Mock
|
||||
PreferredConstructor<?, P> constructor;
|
||||
@Mock
|
||||
Parameter<?, P> parameter;
|
||||
|
||||
@Test
|
||||
@SuppressWarnings({ "unchecked", "rawtypes" })
|
||||
public void instantiatesSimpleObjectCorrectly() {
|
||||
|
||||
when(entity.getType()).thenReturn((Class) Object.class);
|
||||
INSTANCE.createInstance(entity, provider);
|
||||
}
|
||||
|
||||
@Test
|
||||
@SuppressWarnings({ "unchecked", "rawtypes" })
|
||||
public void instantiatesArrayCorrectly() {
|
||||
|
||||
when(entity.getType()).thenReturn((Class) String[][].class);
|
||||
INSTANCE.createInstance(entity, provider);
|
||||
}
|
||||
|
||||
@Test
|
||||
@SuppressWarnings({ "unchecked", "rawtypes" })
|
||||
public void instantiatesTypeWithPreferredConstructorUsingParameterValueProvider() {
|
||||
|
||||
PreferredConstructor constructor = new PreferredConstructorDiscoverer<Foo, P>(Foo.class).getConstructor();
|
||||
|
||||
when(entity.getType()).thenReturn((Class) Foo.class);
|
||||
when(entity.getPersistenceConstructor()).thenReturn(constructor);
|
||||
|
||||
Object instance = INSTANCE.createInstance(entity, provider);
|
||||
|
||||
assertTrue(instance instanceof Foo);
|
||||
verify(provider, times(1)).getParameterValue((Parameter) constructor.getParameters().iterator().next());
|
||||
}
|
||||
|
||||
/**
|
||||
* @see DATACMNS-134
|
||||
*/
|
||||
@Test
|
||||
public void createsInnerClassInstanceCorrectly() {
|
||||
|
||||
BasicPersistentEntity<Inner, P> entity = new BasicPersistentEntity<Inner, P>(ClassTypeInformation.from(Inner.class));
|
||||
PreferredConstructor<Inner, P> constructor = entity.getPersistenceConstructor();
|
||||
Parameter<Object, P> parameter = constructor.getParameters().iterator().next();
|
||||
|
||||
final Object outer = new Outer();
|
||||
|
||||
when(provider.getParameterValue(parameter)).thenReturn(outer);
|
||||
final Inner instance = INSTANCE.createInstance(entity, provider);
|
||||
|
||||
assertThat(instance, is(notNullValue()));
|
||||
|
||||
// Hack to check syntheic field as compiles create different field names (e.g. this$0, this$1)
|
||||
ReflectionUtils.doWithFields(Inner.class, new FieldCallback() {
|
||||
public void doWith(Field field) throws IllegalArgumentException, IllegalAccessException {
|
||||
if (field.isSynthetic() && field.getName().startsWith("this$")) {
|
||||
ReflectionUtils.makeAccessible(field);
|
||||
assertThat(ReflectionUtils.getField(field, instance), is(outer));
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
static class Foo {
|
||||
|
||||
Foo(String foo) {
|
||||
|
||||
}
|
||||
}
|
||||
|
||||
static class Outer {
|
||||
|
||||
class Inner {
|
||||
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,73 @@
|
||||
/*
|
||||
* Copyright 2012 the original author or authors.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
package org.springframework.data.convert;
|
||||
|
||||
import static org.hamcrest.CoreMatchers.*;
|
||||
import static org.junit.Assert.*;
|
||||
|
||||
import org.junit.Test;
|
||||
import org.springframework.data.util.ClassTypeInformation;
|
||||
import org.springframework.data.util.TypeInformation;
|
||||
|
||||
/**
|
||||
*
|
||||
* @author Oliver Gierke
|
||||
*/
|
||||
public class SimpleTypeInformationMapperUnitTests {
|
||||
|
||||
@Test
|
||||
@SuppressWarnings({ "rawtypes" })
|
||||
public void resolvesTypeByLoadingClass() {
|
||||
|
||||
TypeInformationMapper mapper = new SimpleTypeInformationMapper();
|
||||
TypeInformation type = mapper.resolveTypeFrom("java.lang.String");
|
||||
|
||||
TypeInformation expected = ClassTypeInformation.from(String.class);
|
||||
|
||||
assertThat(type, is(expected));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void returnsNullForNonStringKey() {
|
||||
|
||||
TypeInformationMapper mapper = new SimpleTypeInformationMapper();
|
||||
assertThat(mapper.resolveTypeFrom(new Object()), is(nullValue()));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void returnsNullForEmptyTypeKey() {
|
||||
|
||||
TypeInformationMapper mapper = new SimpleTypeInformationMapper();
|
||||
assertThat(mapper.resolveTypeFrom(""), is(nullValue()));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void returnsNullForUnloadableClass() {
|
||||
|
||||
TypeInformationMapper mapper = new SimpleTypeInformationMapper();
|
||||
assertThat(mapper.resolveTypeFrom("Foo"), is(nullValue()));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void usesFullyQualifiedClassNameAsTypeKey() {
|
||||
|
||||
TypeInformationMapper mapper = new SimpleTypeInformationMapper();
|
||||
Object alias = mapper.createAliasFor(ClassTypeInformation.from(String.class));
|
||||
|
||||
assertTrue(alias instanceof String);
|
||||
assertThat(alias, is((Object) String.class.getName()));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,27 @@
|
||||
package org.springframework.data.domain;
|
||||
|
||||
import static org.junit.Assert.*;
|
||||
|
||||
import org.junit.Test;
|
||||
import org.springframework.data.domain.Sort.Direction;
|
||||
|
||||
/**
|
||||
* Unit test for {@link Direction}.
|
||||
*
|
||||
* @author Oliver Gierke
|
||||
*/
|
||||
public class DirectionUnitTests {
|
||||
|
||||
@Test
|
||||
public void jpaValueMapping() throws Exception {
|
||||
|
||||
assertEquals(Direction.ASC, Direction.fromString("asc"));
|
||||
assertEquals(Direction.DESC, Direction.fromString("desc"));
|
||||
}
|
||||
|
||||
@Test(expected = IllegalArgumentException.class)
|
||||
public void rejectsInvalidString() throws Exception {
|
||||
|
||||
Direction.fromString("foo");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,93 @@
|
||||
/*
|
||||
* Copyright 2008-2010 the original author or authors.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
|
||||
* use this file except in compliance with the License. You may obtain a copy of
|
||||
* the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
|
||||
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
|
||||
* License for the specific language governing permissions and limitations under
|
||||
* the License.
|
||||
*/
|
||||
|
||||
package org.springframework.data.domain;
|
||||
|
||||
import static org.hamcrest.CoreMatchers.*;
|
||||
import static org.junit.Assert.*;
|
||||
import static org.springframework.data.domain.UnitTestUtils.*;
|
||||
|
||||
import java.util.Arrays;
|
||||
import java.util.Collections;
|
||||
import java.util.List;
|
||||
|
||||
import org.junit.Test;
|
||||
|
||||
/**
|
||||
* Unit test for {@link PageImpl}.
|
||||
*
|
||||
* @author Oliver Gierke
|
||||
*/
|
||||
public class PageImplUnitTests {
|
||||
|
||||
@Test
|
||||
public void assertEqualsForSimpleSetup() throws Exception {
|
||||
|
||||
PageImpl<String> page = new PageImpl<String>(Arrays.asList("Foo"));
|
||||
|
||||
assertEqualsAndHashcode(page, page);
|
||||
assertEqualsAndHashcode(page, new PageImpl<String>(Arrays.asList("Foo")));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void assertEqualsForComplexSetup() throws Exception {
|
||||
|
||||
Pageable pageable = new PageRequest(0, 10);
|
||||
List<String> content = Arrays.asList("Foo");
|
||||
|
||||
PageImpl<String> page = new PageImpl<String>(content, pageable, 100);
|
||||
|
||||
assertEqualsAndHashcode(page, page);
|
||||
|
||||
assertEqualsAndHashcode(page, new PageImpl<String>(content, pageable, 100));
|
||||
|
||||
assertNotEqualsAndHashcode(page, new PageImpl<String>(content, pageable, 90));
|
||||
|
||||
assertNotEqualsAndHashcode(page, new PageImpl<String>(content, new PageRequest(1, 10), 100));
|
||||
|
||||
assertNotEqualsAndHashcode(page, new PageImpl<String>(content, new PageRequest(0, 15), 100));
|
||||
}
|
||||
|
||||
@Test(expected = IllegalArgumentException.class)
|
||||
public void preventsNullContentForSimpleSetup() throws Exception {
|
||||
|
||||
new PageImpl<Object>(null);
|
||||
}
|
||||
|
||||
@Test(expected = IllegalArgumentException.class)
|
||||
public void preventsNullContentForAdvancedSetup() throws Exception {
|
||||
|
||||
new PageImpl<Object>(null, null, 0);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void createsPageForEmptyContentCorrectly() {
|
||||
List<String> list = Collections.emptyList();
|
||||
Page<String> page = new PageImpl<String>(list);
|
||||
assertThat(page.getContent(), is(list));
|
||||
assertThat(page.getNumber(), is(0));
|
||||
assertThat(page.getNumberOfElements(), is(0));
|
||||
assertThat(page.getSize(), is(0));
|
||||
assertThat(page.getSort(), is((Sort) null));
|
||||
assertThat(page.getTotalElements(), is(0L));
|
||||
assertThat(page.getTotalPages(), is(0));
|
||||
assertThat(page.hasNextPage(), is(false));
|
||||
assertThat(page.hasPreviousPage(), is(false));
|
||||
assertThat(page.isFirstPage(), is(true));
|
||||
assertThat(page.isLastPage(), is(true));
|
||||
assertThat(page.hasContent(), is(false));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,88 @@
|
||||
/*
|
||||
* Copyright 2008-2010 the original author or authors.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
|
||||
* use this file except in compliance with the License. You may obtain a copy of
|
||||
* the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
|
||||
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
|
||||
* License for the specific language governing permissions and limitations under
|
||||
* the License.
|
||||
*/
|
||||
|
||||
package org.springframework.data.domain;
|
||||
|
||||
import static org.springframework.data.domain.UnitTestUtils.*;
|
||||
|
||||
import org.junit.Test;
|
||||
import org.springframework.data.domain.Sort.Direction;
|
||||
|
||||
/**
|
||||
* Unit test for {@link PageRequest}.
|
||||
*
|
||||
* @author Oliver Gierke
|
||||
*/
|
||||
public class PageRequestUnitTests {
|
||||
|
||||
@Test(expected = IllegalArgumentException.class)
|
||||
public void preventsNegativePage() {
|
||||
|
||||
new PageRequest(-1, 10);
|
||||
}
|
||||
|
||||
@Test(expected = IllegalArgumentException.class)
|
||||
public void preventsNegativeSize() {
|
||||
|
||||
new PageRequest(0, -1);
|
||||
}
|
||||
|
||||
@Test(expected = IllegalArgumentException.class)
|
||||
public void preventsZeroSize() {
|
||||
|
||||
new PageRequest(0, 0);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void equalsRegardsSortCorrectly() {
|
||||
|
||||
Sort sort = new Sort(Direction.DESC, "foo");
|
||||
PageRequest request = new PageRequest(0, 10, sort);
|
||||
|
||||
// Equals itself
|
||||
assertEqualsAndHashcode(request, request);
|
||||
|
||||
// Equals another instance with same setup
|
||||
assertEqualsAndHashcode(request, new PageRequest(0, 10, sort));
|
||||
|
||||
// Equals without sort entirely
|
||||
assertEqualsAndHashcode(new PageRequest(0, 10), new PageRequest(0, 10));
|
||||
|
||||
// Is not equal to instance without sort
|
||||
assertNotEqualsAndHashcode(request, new PageRequest(0, 10));
|
||||
|
||||
// Is not equal to instance with another sort
|
||||
assertNotEqualsAndHashcode(request, new PageRequest(0, 10, Direction.ASC, "foo"));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void equalsHonoursPageAndSize() {
|
||||
|
||||
PageRequest request = new PageRequest(0, 10);
|
||||
|
||||
// Equals itself
|
||||
assertEqualsAndHashcode(request, request);
|
||||
|
||||
// Equals same setup
|
||||
assertEqualsAndHashcode(request, new PageRequest(0, 10));
|
||||
|
||||
// Does not equal on different page
|
||||
assertNotEqualsAndHashcode(request, new PageRequest(1, 10));
|
||||
|
||||
// Does not equal on different size
|
||||
assertNotEqualsAndHashcode(request, new PageRequest(0, 11));
|
||||
}
|
||||
}
|
||||
101
src/test/java/org/springframework/data/domain/SortUnitTests.java
Normal file
101
src/test/java/org/springframework/data/domain/SortUnitTests.java
Normal file
@@ -0,0 +1,101 @@
|
||||
/*
|
||||
* Copyright 2008-2010 the original author or authors.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
|
||||
* use this file except in compliance with the License. You may obtain a copy of
|
||||
* the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
|
||||
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
|
||||
* License for the specific language governing permissions and limitations under
|
||||
* the License.
|
||||
*/
|
||||
|
||||
package org.springframework.data.domain;
|
||||
|
||||
import static org.hamcrest.CoreMatchers.*;
|
||||
import static org.junit.Assert.*;
|
||||
|
||||
import org.junit.Test;
|
||||
import org.springframework.data.domain.Sort.Direction;
|
||||
|
||||
/**
|
||||
* Unit test for {@link Sort}.
|
||||
*
|
||||
* @author Oliver Gierke
|
||||
*/
|
||||
public class SortUnitTests {
|
||||
|
||||
/**
|
||||
* Asserts that the class applies the default sort order if no order or {@code null} was provided.
|
||||
*
|
||||
* @throws Exception
|
||||
*/
|
||||
@Test
|
||||
public void appliesDefaultForOrder() throws Exception {
|
||||
|
||||
assertEquals(Sort.DEFAULT_DIRECTION, new Sort("foo").iterator().next().getDirection());
|
||||
assertEquals(Sort.DEFAULT_DIRECTION, new Sort((Direction) null, "foo").iterator().next().getDirection());
|
||||
}
|
||||
|
||||
/**
|
||||
* Asserts that the class rejects {@code null} as properties array.
|
||||
*
|
||||
* @throws Exception
|
||||
*/
|
||||
@Test(expected = IllegalArgumentException.class)
|
||||
public void preventsNullProperties() throws Exception {
|
||||
|
||||
new Sort(Direction.ASC, (String[]) null);
|
||||
}
|
||||
|
||||
/**
|
||||
* Asserts that the class rejects {@code null} values in the properties array.
|
||||
*
|
||||
* @throws Exception
|
||||
*/
|
||||
@Test(expected = IllegalArgumentException.class)
|
||||
public void preventsNullProperty() throws Exception {
|
||||
|
||||
new Sort(Direction.ASC, (String) null);
|
||||
}
|
||||
|
||||
/**
|
||||
* Asserts that the class rejects empty strings in the properties array.
|
||||
*
|
||||
* @throws Exception
|
||||
*/
|
||||
@Test(expected = IllegalArgumentException.class)
|
||||
public void preventsEmptyProperty() throws Exception {
|
||||
|
||||
new Sort(Direction.ASC, "");
|
||||
}
|
||||
|
||||
/**
|
||||
* Asserts that the class rejects no properties given at all.
|
||||
*
|
||||
* @throws Exception
|
||||
*/
|
||||
@Test(expected = IllegalArgumentException.class)
|
||||
public void preventsNoProperties() throws Exception {
|
||||
|
||||
new Sort(Direction.ASC);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void allowsCombiningSorts() {
|
||||
|
||||
Sort sort = new Sort("foo").and(new Sort("bar"));
|
||||
assertThat(sort, hasItems(new Sort.Order("foo"), new Sort.Order("bar")));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void handlesAdditionalNullSort() {
|
||||
|
||||
Sort sort = new Sort("foo").and(null);
|
||||
assertThat(sort, hasItem(new Sort.Order("foo")));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,39 @@
|
||||
package org.springframework.data.domain;
|
||||
|
||||
import static org.junit.Assert.*;
|
||||
|
||||
/**
|
||||
* @author Oliver Gierke
|
||||
*/
|
||||
public abstract class UnitTestUtils {
|
||||
|
||||
private UnitTestUtils() {
|
||||
|
||||
}
|
||||
|
||||
/**
|
||||
* Asserts that delivered objects both equal each other as well as return the same hash code.
|
||||
*
|
||||
* @param first
|
||||
* @param second
|
||||
*/
|
||||
public static void assertEqualsAndHashcode(Object first, Object second) {
|
||||
|
||||
assertEquals(first, second);
|
||||
assertEquals(second, first);
|
||||
assertEquals(first.hashCode(), second.hashCode());
|
||||
}
|
||||
|
||||
/**
|
||||
* Asserts that both objects are not equal to each other and differ in hash code, too.
|
||||
*
|
||||
* @param first
|
||||
* @param second
|
||||
*/
|
||||
public static void assertNotEqualsAndHashcode(Object first, Object second) {
|
||||
|
||||
assertFalse(first.equals(second));
|
||||
assertFalse(second.equals(first));
|
||||
assertFalse(first.hashCode() == second.hashCode());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,160 @@
|
||||
/*
|
||||
* Copyright 2012 the original author or authors.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
package org.springframework.data.domain.jaxb;
|
||||
|
||||
import static org.hamcrest.CoreMatchers.*;
|
||||
import static org.junit.Assert.*;
|
||||
|
||||
import java.io.StringWriter;
|
||||
import java.util.Arrays;
|
||||
import java.util.List;
|
||||
import java.util.Scanner;
|
||||
|
||||
import javax.xml.bind.JAXBContext;
|
||||
import javax.xml.bind.Marshaller;
|
||||
import javax.xml.bind.Unmarshaller;
|
||||
import javax.xml.bind.annotation.XmlAccessType;
|
||||
import javax.xml.bind.annotation.XmlAccessorType;
|
||||
import javax.xml.bind.annotation.XmlAttribute;
|
||||
import javax.xml.bind.annotation.XmlElement;
|
||||
import javax.xml.bind.annotation.XmlRootElement;
|
||||
import javax.xml.bind.annotation.adapters.XmlJavaTypeAdapter;
|
||||
|
||||
import org.junit.After;
|
||||
import org.junit.Before;
|
||||
import org.junit.Test;
|
||||
import org.springframework.core.io.ClassPathResource;
|
||||
import org.springframework.core.io.Resource;
|
||||
import org.springframework.data.domain.Page;
|
||||
import org.springframework.data.domain.PageImpl;
|
||||
import org.springframework.data.domain.PageRequest;
|
||||
import org.springframework.data.domain.Pageable;
|
||||
import org.springframework.data.domain.Sort;
|
||||
import org.springframework.data.domain.Sort.Direction;
|
||||
import org.springframework.hateoas.Link;
|
||||
|
||||
/**
|
||||
* Unit test for custom JAXB conversions for Spring Data value objects.
|
||||
*
|
||||
* @author Oliver Gierke
|
||||
*/
|
||||
public class SpringDataJaxbUnitTests {
|
||||
|
||||
Marshaller marshaller;
|
||||
Unmarshaller unmarshaller;
|
||||
|
||||
Sort sort = new Sort(Direction.ASC, "firstname", "lastname");
|
||||
Pageable reference = new PageRequest(2, 15, sort);
|
||||
Resource resource = new ClassPathResource("pageable.xml", this.getClass());
|
||||
Resource schemaFile = new ClassPathResource("spring-data-jaxb.xsd", this.getClass());
|
||||
|
||||
Scanner scanner;
|
||||
|
||||
@Before
|
||||
public void setUp() throws Exception {
|
||||
|
||||
JAXBContext context = JAXBContext.newInstance("org.springframework.data.domain.jaxb");
|
||||
|
||||
marshaller = context.createMarshaller();
|
||||
marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
|
||||
|
||||
unmarshaller = context.createUnmarshaller();
|
||||
|
||||
scanner = new Scanner(resource.getFile());
|
||||
}
|
||||
|
||||
@After
|
||||
public void tearDown() {
|
||||
scanner.close();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void usesCustomTypeAdapterForPageRequests() throws Exception {
|
||||
|
||||
StringWriter writer = new StringWriter();
|
||||
Wrapper wrapper = new Wrapper();
|
||||
wrapper.pageable = reference;
|
||||
wrapper.sort = sort;
|
||||
wrapper.pageableWithoutSort = new PageRequest(10, 20);
|
||||
marshaller.marshal(wrapper, writer);
|
||||
|
||||
for (String line : writer.toString().split("\n")) {
|
||||
assertThat(scanner.hasNextLine(), is(true));
|
||||
assertThat(line, is(scanner.nextLine()));
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
public void readsPageRequest() throws Exception {
|
||||
|
||||
Object result = unmarshaller.unmarshal(resource.getFile());
|
||||
|
||||
assertThat(result, is(instanceOf(Wrapper.class)));
|
||||
assertThat(((Wrapper) result).pageable, is(reference));
|
||||
assertThat(((Wrapper) result).sort, is(sort));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void writesPlainPage() throws Exception {
|
||||
|
||||
PageWrapper wrapper = new PageWrapper();
|
||||
Content content = new Content();
|
||||
content.name = "Foo";
|
||||
wrapper.page = new PageImpl<Content>(Arrays.asList(content));
|
||||
wrapper.pageWithLinks = new PageImpl<Content>(Arrays.asList(content));
|
||||
|
||||
marshaller.marshal(wrapper, new StringWriter());
|
||||
}
|
||||
|
||||
@XmlRootElement
|
||||
@XmlAccessorType(XmlAccessType.FIELD)
|
||||
static class Wrapper {
|
||||
|
||||
@XmlElement(name = "page-request", namespace = SpringDataJaxb.NAMESPACE)
|
||||
Pageable pageable;
|
||||
|
||||
@XmlElement(name = "page-request-without-sort", namespace = SpringDataJaxb.NAMESPACE)
|
||||
Pageable pageableWithoutSort;
|
||||
|
||||
@XmlElement(name = "sort", namespace = SpringDataJaxb.NAMESPACE)
|
||||
Sort sort;
|
||||
}
|
||||
|
||||
@XmlRootElement(name = "wrapper", namespace = SpringDataJaxb.NAMESPACE)
|
||||
static class PageWrapper {
|
||||
|
||||
Page<Content> page;
|
||||
|
||||
@XmlElement(name = "page-with-links")
|
||||
@XmlJavaTypeAdapter(LinkedPageAdapter.class)
|
||||
Page<Content> pageWithLinks;
|
||||
}
|
||||
|
||||
@XmlRootElement
|
||||
static class Content {
|
||||
|
||||
@XmlAttribute
|
||||
String name;
|
||||
}
|
||||
|
||||
static class LinkedPageAdapter extends PageAdapter {
|
||||
|
||||
@Override
|
||||
protected List<Link> getLinks(Page<?> source) {
|
||||
return Arrays.asList(new Link(Link.REL_NEXT, "next"), new Link(Link.REL_PREVIOUS, "previous"));
|
||||
}
|
||||
}
|
||||
}
|
||||
96
src/test/java/org/springframework/data/history/RevisionUnitTests.java
Executable file
96
src/test/java/org/springframework/data/history/RevisionUnitTests.java
Executable file
@@ -0,0 +1,96 @@
|
||||
/*
|
||||
* Copyright 2012 the original author or authors.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
package org.springframework.data.history;
|
||||
|
||||
import static org.hamcrest.CoreMatchers.*;
|
||||
import static org.junit.Assert.*;
|
||||
import static org.mockito.Mockito.*;
|
||||
|
||||
import java.util.Arrays;
|
||||
import java.util.Collections;
|
||||
import java.util.List;
|
||||
|
||||
import org.joda.time.DateTime;
|
||||
import org.junit.Test;
|
||||
import org.junit.runner.RunWith;
|
||||
import org.mockito.Mock;
|
||||
import org.mockito.runners.MockitoJUnitRunner;
|
||||
|
||||
/**
|
||||
* Unit tests for {@link RevisionMetadata}.
|
||||
*
|
||||
* @author Oliver Gierke
|
||||
*/
|
||||
@RunWith(MockitoJUnitRunner.class)
|
||||
public class RevisionUnitTests {
|
||||
|
||||
@Mock
|
||||
RevisionMetadata<Integer> firstMetadata, secondMetadata;
|
||||
|
||||
@Test
|
||||
@SuppressWarnings("unchecked")
|
||||
public void comparesCorrectly() {
|
||||
|
||||
when(firstMetadata.getRevisionNumber()).thenReturn(1);
|
||||
when(secondMetadata.getRevisionNumber()).thenReturn(2);
|
||||
|
||||
Revision<Integer, Object> first = new Revision<Integer, Object>(firstMetadata, new Object());
|
||||
Revision<Integer, Object> second = new Revision<Integer, Object>(secondMetadata, new Object());
|
||||
|
||||
List<Revision<Integer, Object>> revisions = Arrays.asList(second, first);
|
||||
Collections.sort(revisions);
|
||||
|
||||
assertThat(revisions.get(0), is(first));
|
||||
assertThat(revisions.get(1), is(second));
|
||||
}
|
||||
|
||||
/**
|
||||
* @see DATACMNS-187
|
||||
*/
|
||||
@Test
|
||||
public void returnsRevisionNumber() {
|
||||
|
||||
when(firstMetadata.getRevisionNumber()).thenReturn(4711);
|
||||
|
||||
Revision<Integer, Object> revision = new Revision<Integer, Object>(firstMetadata, new Object());
|
||||
|
||||
assertThat(revision.getRevisionNumber(), is(4711));
|
||||
}
|
||||
|
||||
/**
|
||||
* @see DATACMNS-187
|
||||
*/
|
||||
@Test
|
||||
public void returnsRevisionDate() {
|
||||
|
||||
DateTime reference = new DateTime();
|
||||
when(firstMetadata.getRevisionDate()).thenReturn(reference);
|
||||
|
||||
Revision<Integer, Object> revision = new Revision<Integer, Object>(firstMetadata, new Object());
|
||||
|
||||
assertThat(revision.getRevisionDate(), is(reference));
|
||||
}
|
||||
|
||||
/**
|
||||
* @see DATACMNS-218
|
||||
*/
|
||||
@Test
|
||||
public void returnsRevisionMetadata() {
|
||||
|
||||
Revision<Integer, Object> revision = new Revision<Integer, Object>(firstMetadata, new Object());
|
||||
assertThat(revision.getMetadata(), is(firstMetadata));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,110 @@
|
||||
/*
|
||||
* Copyright 2012 the original author or authors.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
package org.springframework.data.history;
|
||||
|
||||
import static org.hamcrest.CoreMatchers.*;
|
||||
import static org.junit.Assert.*;
|
||||
import static org.mockito.Mockito.*;
|
||||
|
||||
import java.util.Arrays;
|
||||
import java.util.Iterator;
|
||||
|
||||
import org.junit.Before;
|
||||
import org.junit.Test;
|
||||
import org.junit.runner.RunWith;
|
||||
import org.mockito.Mock;
|
||||
import org.mockito.runners.MockitoJUnitRunner;
|
||||
|
||||
/**
|
||||
* Unit tests for {@link Revisions}.
|
||||
*
|
||||
* @author Oliver Gierke
|
||||
*/
|
||||
@RunWith(MockitoJUnitRunner.class)
|
||||
public class RevisionsUnitTests {
|
||||
|
||||
@Mock
|
||||
RevisionMetadata<Integer> first, second;
|
||||
Revision<Integer, Object> firstRevision, secondRevision;
|
||||
|
||||
@Before
|
||||
public void setUp() {
|
||||
|
||||
when(first.getRevisionNumber()).thenReturn(0);
|
||||
when(second.getRevisionNumber()).thenReturn(10);
|
||||
|
||||
firstRevision = new Revision<Integer, Object>(first, new Object());
|
||||
secondRevision = new Revision<Integer, Object>(second, new Object());
|
||||
}
|
||||
|
||||
@Test
|
||||
@SuppressWarnings("unchecked")
|
||||
public void returnsCorrectLatestRevision() {
|
||||
|
||||
Revisions<Integer, Object> revisions = new Revisions<Integer, Object>(Arrays.asList(firstRevision, secondRevision));
|
||||
assertThat(revisions.getLatestRevision(), is(secondRevision));
|
||||
}
|
||||
|
||||
@Test
|
||||
@SuppressWarnings("unchecked")
|
||||
public void iteratesInCorrectOrder() {
|
||||
|
||||
Revisions<Integer, Object> revisions = new Revisions<Integer, Object>(Arrays.asList(firstRevision, secondRevision));
|
||||
Iterator<Revision<Integer, Object>> iterator = revisions.iterator();
|
||||
|
||||
assertThat(iterator.hasNext(), is(true));
|
||||
assertThat(iterator.next(), is(firstRevision));
|
||||
assertThat(iterator.hasNext(), is(true));
|
||||
assertThat(iterator.next(), is(secondRevision));
|
||||
assertThat(iterator.hasNext(), is(false));
|
||||
}
|
||||
|
||||
@Test
|
||||
@SuppressWarnings("unchecked")
|
||||
public void reversedRevisionsStillReturnsCorrectLatestRevision() {
|
||||
|
||||
Revisions<Integer, Object> revisions = new Revisions<Integer, Object>(Arrays.asList(firstRevision, secondRevision));
|
||||
assertThat(revisions.reverse().getLatestRevision(), is(secondRevision));
|
||||
}
|
||||
|
||||
@Test
|
||||
@SuppressWarnings("unchecked")
|
||||
public void iteratesReversedRevisionsInCorrectOrder() {
|
||||
|
||||
Revisions<Integer, Object> revisions = new Revisions<Integer, Object>(Arrays.asList(firstRevision, secondRevision));
|
||||
Iterator<Revision<Integer, Object>> iterator = revisions.reverse().iterator();
|
||||
|
||||
assertThat(iterator.hasNext(), is(true));
|
||||
assertThat(iterator.next(), is(secondRevision));
|
||||
assertThat(iterator.hasNext(), is(true));
|
||||
assertThat(iterator.next(), is(firstRevision));
|
||||
assertThat(iterator.hasNext(), is(false));
|
||||
}
|
||||
|
||||
@Test
|
||||
@SuppressWarnings("unchecked")
|
||||
public void forcesInvalidlyOrderedRevisionsToBeOrdered() {
|
||||
|
||||
Revisions<Integer, Object> revisions = new Revisions<Integer, Object>(Arrays.asList(secondRevision, firstRevision));
|
||||
Iterator<Revision<Integer, Object>> iterator = revisions.iterator();
|
||||
|
||||
assertThat(iterator.hasNext(), is(true));
|
||||
assertThat(iterator.next(), is(firstRevision));
|
||||
assertThat(iterator.hasNext(), is(true));
|
||||
assertThat(iterator.next(), is(secondRevision));
|
||||
assertThat(iterator.hasNext(), is(false));
|
||||
}
|
||||
}
|
||||
31
src/test/java/org/springframework/data/mapping/Child.java
Normal file
31
src/test/java/org/springframework/data/mapping/Child.java
Normal file
@@ -0,0 +1,31 @@
|
||||
/*
|
||||
* Copyright (c) 2011 by the original author(s).
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
package org.springframework.data.mapping;
|
||||
|
||||
import org.springframework.data.annotation.Persistent;
|
||||
|
||||
/**
|
||||
* @author Jon Brisbin <jbrisbin@vmware.com>
|
||||
*/
|
||||
@Persistent
|
||||
public class Child extends PersonWithId {
|
||||
|
||||
public Child(Integer ssn, String firstName, String lastName) {
|
||||
super(ssn, firstName, lastName);
|
||||
}
|
||||
|
||||
}
|
||||
33
src/test/java/org/springframework/data/mapping/Document.java
Normal file
33
src/test/java/org/springframework/data/mapping/Document.java
Normal file
@@ -0,0 +1,33 @@
|
||||
/*
|
||||
* Copyright (c) 2011 by the original author(s).
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
package org.springframework.data.mapping;
|
||||
|
||||
import java.lang.annotation.ElementType;
|
||||
import java.lang.annotation.Retention;
|
||||
import java.lang.annotation.RetentionPolicy;
|
||||
import java.lang.annotation.Target;
|
||||
|
||||
import org.springframework.data.annotation.Persistent;
|
||||
|
||||
/**
|
||||
* @author Jon Brisbin <jbrisbin@vmware.com>
|
||||
*/
|
||||
@Retention(RetentionPolicy.RUNTIME)
|
||||
@Target({ ElementType.TYPE, ElementType.FIELD })
|
||||
@Persistent
|
||||
public @interface Document {
|
||||
}
|
||||
@@ -0,0 +1,107 @@
|
||||
/*
|
||||
* Copyright 2011-2012 the original author or authors.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
package org.springframework.data.mapping;
|
||||
|
||||
import static org.junit.Assert.*;
|
||||
|
||||
import java.beans.PropertyDescriptor;
|
||||
import java.lang.reflect.Field;
|
||||
import java.util.Collections;
|
||||
|
||||
import org.junit.Before;
|
||||
import org.junit.Test;
|
||||
import org.springframework.data.mapping.context.AbstractMappingContext;
|
||||
import org.springframework.data.mapping.model.AnnotationBasedPersistentProperty;
|
||||
import org.springframework.data.mapping.model.BasicPersistentEntity;
|
||||
import org.springframework.data.mapping.model.MutablePersistentEntity;
|
||||
import org.springframework.data.mapping.model.SimpleTypeHolder;
|
||||
import org.springframework.data.util.TypeInformation;
|
||||
|
||||
/**
|
||||
* Integration tests for Mapping metadata.
|
||||
*
|
||||
* @author Jon Brisbin
|
||||
* @author Oliver Gierke
|
||||
*/
|
||||
public class MappingMetadataTests {
|
||||
|
||||
SampleMappingContext ctx;
|
||||
|
||||
@Before
|
||||
public void setup() {
|
||||
ctx = new SampleMappingContext();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testPojoWithId() {
|
||||
|
||||
ctx.setInitialEntitySet(Collections.singleton(PersonWithId.class));
|
||||
ctx.initialize();
|
||||
|
||||
PersistentEntity<?, SampleProperty> person = ctx.getPersistentEntity(PersonWithId.class);
|
||||
assertNotNull(person.getIdProperty());
|
||||
assertEquals(String.class, person.getIdProperty().getType());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testAssociations() {
|
||||
|
||||
ctx.setInitialEntitySet(Collections.singleton(PersonWithChildren.class));
|
||||
ctx.initialize();
|
||||
|
||||
PersistentEntity<?, SampleProperty> person = ctx.getPersistentEntity(PersonWithChildren.class);
|
||||
person.doWithAssociations(new AssociationHandler<MappingMetadataTests.SampleProperty>() {
|
||||
public void doWithAssociation(Association<SampleProperty> association) {
|
||||
assertEquals(Child.class, association.getInverse().getComponentType());
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
public interface SampleProperty extends PersistentProperty<SampleProperty> {
|
||||
}
|
||||
|
||||
public static class SampleMappingContext extends
|
||||
AbstractMappingContext<MutablePersistentEntity<?, SampleProperty>, SampleProperty> {
|
||||
|
||||
@Override
|
||||
protected <T> MutablePersistentEntity<?, SampleProperty> createPersistentEntity(TypeInformation<T> typeInformation) {
|
||||
|
||||
return new BasicPersistentEntity<T, MappingMetadataTests.SampleProperty>(typeInformation);
|
||||
}
|
||||
|
||||
@Override
|
||||
protected SampleProperty createPersistentProperty(Field field, PropertyDescriptor descriptor,
|
||||
MutablePersistentEntity<?, SampleProperty> owner, SimpleTypeHolder simpleTypeHolder) {
|
||||
return new SamplePropertyImpl(field, descriptor, owner, simpleTypeHolder);
|
||||
}
|
||||
}
|
||||
|
||||
public static class SamplePropertyImpl extends AnnotationBasedPersistentProperty<SampleProperty> implements
|
||||
SampleProperty {
|
||||
|
||||
public SamplePropertyImpl(Field field, PropertyDescriptor propertyDescriptor,
|
||||
PersistentEntity<?, SampleProperty> owner, SimpleTypeHolder simpleTypeHolder) {
|
||||
|
||||
super(field, propertyDescriptor, owner, simpleTypeHolder);
|
||||
}
|
||||
|
||||
@Override
|
||||
protected Association<SampleProperty> createAssociation() {
|
||||
|
||||
return new Association<MappingMetadataTests.SampleProperty>(this, null);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,96 @@
|
||||
/*
|
||||
* Copyright 2012 the original author or authors.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
package org.springframework.data.mapping;
|
||||
|
||||
import static org.hamcrest.CoreMatchers.*;
|
||||
import static org.junit.Assert.*;
|
||||
|
||||
import java.lang.annotation.Annotation;
|
||||
|
||||
import org.junit.Test;
|
||||
import org.junit.runner.RunWith;
|
||||
import org.mockito.Mock;
|
||||
import org.mockito.runners.MockitoJUnitRunner;
|
||||
import org.springframework.data.mapping.PreferredConstructor.Parameter;
|
||||
import org.springframework.data.util.ClassTypeInformation;
|
||||
import org.springframework.data.util.TypeInformation;
|
||||
|
||||
/**
|
||||
* Unit tests for {@link Parameter}.
|
||||
*
|
||||
* @author Oliver Gierke
|
||||
*/
|
||||
@RunWith(MockitoJUnitRunner.class)
|
||||
public class ParameterUnitTests<P extends PersistentProperty<P>> {
|
||||
|
||||
@Mock
|
||||
PersistentEntity<Object, P> entity;
|
||||
@Mock
|
||||
PersistentEntity<String, P> stringEntity;
|
||||
|
||||
TypeInformation<Object> type = ClassTypeInformation.from(Object.class);
|
||||
Annotation[] annotations = new Annotation[0];
|
||||
|
||||
@Test
|
||||
public void twoParametersWithIdenticalSetupEqual() {
|
||||
|
||||
Parameter<Object, P> left = new Parameter<Object, P>("name", type, annotations, entity);
|
||||
Parameter<Object, P> right = new Parameter<Object, P>("name", type, annotations, entity);
|
||||
|
||||
assertThat(left, is(right));
|
||||
assertThat(left.hashCode(), is(right.hashCode()));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void twoParametersWithIdenticalSetupAndNullNameEqual() {
|
||||
|
||||
Parameter<Object, P> left = new Parameter<Object, P>(null, type, annotations, entity);
|
||||
Parameter<Object, P> right = new Parameter<Object, P>(null, type, annotations, entity);
|
||||
|
||||
assertThat(left, is(right));
|
||||
assertThat(left.hashCode(), is(right.hashCode()));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void twoParametersWithIdenticalAndNullEntitySetupEqual() {
|
||||
|
||||
Parameter<Object, P> left = new Parameter<Object, P>("name", type, annotations, null);
|
||||
Parameter<Object, P> right = new Parameter<Object, P>("name", type, annotations, null);
|
||||
|
||||
assertThat(left, is(right));
|
||||
assertThat(left.hashCode(), is(right.hashCode()));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void twoParametersWithDifferentNameAreNotEqual() {
|
||||
|
||||
Parameter<Object, P> left = new Parameter<Object, P>("first", type, annotations, entity);
|
||||
Parameter<Object, P> right = new Parameter<Object, P>("second", type, annotations, entity);
|
||||
|
||||
assertThat(left, is(not(right)));
|
||||
}
|
||||
|
||||
@Test
|
||||
@SuppressWarnings("rawtypes")
|
||||
public void twoParametersWithDifferenTypeAreNotEqual() {
|
||||
|
||||
Parameter left = new Parameter<Object, P>("name", type, annotations, entity);
|
||||
Parameter right = new Parameter<String, P>("name", ClassTypeInformation.from(String.class), annotations,
|
||||
stringEntity);
|
||||
|
||||
assertThat(left, is(not(right)));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,32 @@
|
||||
/*
|
||||
* Copyright (c) 2011 by the original author(s).
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
package org.springframework.data.mapping;
|
||||
|
||||
import static org.hamcrest.CoreMatchers.*;
|
||||
import static org.junit.Assert.*;
|
||||
|
||||
/**
|
||||
* Some test methods that define expected behaviour for {@link PersistentEntity} interface. Implementation test classes
|
||||
* can simply extend that class to get the specs tested against an instance of their implementation.
|
||||
*
|
||||
* @author Oliver Gierke
|
||||
*/
|
||||
public abstract class PersistentEntitySpec {
|
||||
|
||||
public static void assertInvariants(PersistentEntity<?, ?> entity) {
|
||||
assertThat(entity.getName(), is(notNullValue()));
|
||||
}
|
||||
}
|
||||
58
src/test/java/org/springframework/data/mapping/Person.java
Normal file
58
src/test/java/org/springframework/data/mapping/Person.java
Normal file
@@ -0,0 +1,58 @@
|
||||
/*
|
||||
* Copyright (c) 2011 by the original author(s).
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
package org.springframework.data.mapping;
|
||||
|
||||
/**
|
||||
* @author Jon Brisbin <jbrisbin@vmware.com>
|
||||
*/
|
||||
public abstract class Person {
|
||||
|
||||
private Integer ssn;
|
||||
private String firstName;
|
||||
private String lastName;
|
||||
|
||||
protected Person(Integer ssn, String firstName, String lastName) {
|
||||
this.ssn = ssn;
|
||||
this.firstName = firstName;
|
||||
this.lastName = lastName;
|
||||
}
|
||||
|
||||
public Integer getSsn() {
|
||||
return ssn;
|
||||
}
|
||||
|
||||
public void setSsn(Integer ssn) {
|
||||
this.ssn = ssn;
|
||||
}
|
||||
|
||||
public String getFirstName() {
|
||||
return firstName;
|
||||
}
|
||||
|
||||
public void setFirstName(String firstName) {
|
||||
this.firstName = firstName;
|
||||
}
|
||||
|
||||
public String getLastName() {
|
||||
return lastName;
|
||||
}
|
||||
|
||||
public void setLastName(String lastName) {
|
||||
this.lastName = lastName;
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,29 @@
|
||||
/*
|
||||
* Copyright (c) 2011 by the original author(s).
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
package org.springframework.data.mapping;
|
||||
|
||||
/**
|
||||
* @author Jon Brisbin <jbrisbin@vmware.com>
|
||||
*/
|
||||
@Document
|
||||
public class PersonDocument extends Person {
|
||||
|
||||
public PersonDocument(Integer ssn, String firstName, String lastName) {
|
||||
super(ssn, firstName, lastName);
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,29 @@
|
||||
/*
|
||||
* Copyright (c) 2011 by the original author(s).
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
package org.springframework.data.mapping;
|
||||
|
||||
/**
|
||||
* @author Jon Brisbin <jbrisbin@vmware.com>
|
||||
*/
|
||||
@Document
|
||||
public class PersonNoId extends Person {
|
||||
|
||||
public PersonNoId(Integer ssn, String firstName, String lastName) {
|
||||
super(ssn, firstName, lastName);
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,31 @@
|
||||
/*
|
||||
* Copyright (c) 2011 by the original author(s).
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
package org.springframework.data.mapping;
|
||||
|
||||
import org.springframework.data.annotation.Persistent;
|
||||
|
||||
/**
|
||||
* @author Jon Brisbin <jbrisbin@vmware.com>
|
||||
*/
|
||||
@Persistent
|
||||
public class PersonPersistent extends PersonWithId {
|
||||
|
||||
public PersonPersistent(Integer ssn, String firstName, String lastName) {
|
||||
super(ssn, firstName, lastName);
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,47 @@
|
||||
/*
|
||||
* Copyright (c) 2011 by the original author(s).
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
package org.springframework.data.mapping;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
import org.springframework.data.annotation.Id;
|
||||
import org.springframework.data.annotation.Reference;
|
||||
|
||||
/**
|
||||
* @author Jon Brisbin <jbrisbin@vmware.com>
|
||||
*/
|
||||
public class PersonWithChildren extends Person {
|
||||
|
||||
@Id
|
||||
String id;
|
||||
|
||||
@Reference
|
||||
private List<Child> children;
|
||||
|
||||
public PersonWithChildren(Integer ssn, String firstName, String lastName) {
|
||||
super(ssn, firstName, lastName);
|
||||
}
|
||||
|
||||
public List<Child> getChildren() {
|
||||
return children;
|
||||
}
|
||||
|
||||
public void setChildren(List<Child> children) {
|
||||
this.children = children;
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,37 @@
|
||||
/*
|
||||
* Copyright (c) 2011 by the original author(s).
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
package org.springframework.data.mapping;
|
||||
|
||||
import org.springframework.data.annotation.Id;
|
||||
|
||||
/**
|
||||
* @author Jon Brisbin <jbrisbin@vmware.com>
|
||||
*/
|
||||
public class PersonWithId extends Person {
|
||||
|
||||
@Id
|
||||
private String id;
|
||||
|
||||
public PersonWithId(Integer ssn, String firstName, String lastName) {
|
||||
super(ssn, firstName, lastName);
|
||||
}
|
||||
|
||||
public String getId() {
|
||||
return id;
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,150 @@
|
||||
/*
|
||||
* Copyright 2011-2012 by the original author(s).
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
package org.springframework.data.mapping;
|
||||
|
||||
import static org.hamcrest.Matchers.*;
|
||||
import static org.junit.Assert.*;
|
||||
|
||||
import java.util.Iterator;
|
||||
|
||||
import org.junit.Test;
|
||||
import org.springframework.data.annotation.PersistenceConstructor;
|
||||
import org.springframework.data.mapping.PreferredConstructor.Parameter;
|
||||
import org.springframework.data.mapping.PreferredConstructorDiscovererUnitTests.Outer.Inner;
|
||||
import org.springframework.data.mapping.model.BasicPersistentEntity;
|
||||
import org.springframework.data.mapping.model.PreferredConstructorDiscoverer;
|
||||
import org.springframework.data.util.ClassTypeInformation;
|
||||
|
||||
/**
|
||||
* Unit tests for {@link PreferredConstructorDiscoverer}.
|
||||
*
|
||||
* @author Oliver Gierke
|
||||
*/
|
||||
public class PreferredConstructorDiscovererUnitTests<P extends PersistentProperty<P>> {
|
||||
|
||||
@Test
|
||||
public void findsNoArgConstructorForClassWithoutExplicitConstructor() {
|
||||
|
||||
PreferredConstructorDiscoverer<EntityWithoutConstructor, P> discoverer = new PreferredConstructorDiscoverer<EntityWithoutConstructor, P>(
|
||||
EntityWithoutConstructor.class);
|
||||
PreferredConstructor<EntityWithoutConstructor, P> constructor = discoverer.getConstructor();
|
||||
|
||||
assertThat(constructor, is(notNullValue()));
|
||||
assertThat(constructor.isNoArgConstructor(), is(true));
|
||||
assertThat(constructor.isExplicitlyAnnotated(), is(false));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void findsNoArgConstructorForClassWithMultipleConstructorsAndNoArgOne() {
|
||||
|
||||
PreferredConstructorDiscoverer<ClassWithEmptyConstructor, P> discoverer = new PreferredConstructorDiscoverer<ClassWithEmptyConstructor, P>(
|
||||
ClassWithEmptyConstructor.class);
|
||||
PreferredConstructor<ClassWithEmptyConstructor, P> constructor = discoverer.getConstructor();
|
||||
|
||||
assertThat(constructor, is(notNullValue()));
|
||||
assertThat(constructor.isNoArgConstructor(), is(true));
|
||||
assertThat(constructor.isExplicitlyAnnotated(), is(false));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void doesNotThrowExceptionForMultipleConstructorsAndNoNoArgConstructorWithoutAnnotation() {
|
||||
|
||||
PreferredConstructorDiscoverer<ClassWithMultipleConstructorsWithoutEmptyOne, P> discoverer = new PreferredConstructorDiscoverer<ClassWithMultipleConstructorsWithoutEmptyOne, P>(
|
||||
ClassWithMultipleConstructorsWithoutEmptyOne.class);
|
||||
assertThat(discoverer.getConstructor(), is(nullValue()));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void usesConstructorWithAnnotationOverEveryOther() {
|
||||
|
||||
PreferredConstructorDiscoverer<ClassWithMultipleConstructorsAndAnnotation, P> discoverer = new PreferredConstructorDiscoverer<ClassWithMultipleConstructorsAndAnnotation, P>(
|
||||
ClassWithMultipleConstructorsAndAnnotation.class);
|
||||
PreferredConstructor<ClassWithMultipleConstructorsAndAnnotation, P> constructor = discoverer.getConstructor();
|
||||
|
||||
assertThat(constructor, is(notNullValue()));
|
||||
assertThat(constructor.isNoArgConstructor(), is(false));
|
||||
assertThat(constructor.isExplicitlyAnnotated(), is(true));
|
||||
|
||||
assertThat(constructor.hasParameters(), is(true));
|
||||
Iterator<Parameter<Object, P>> parameters = constructor.getParameters().iterator();
|
||||
|
||||
Parameter<?, P> parameter = parameters.next();
|
||||
assertThat(parameter.getType().getType(), typeCompatibleWith(Long.class));
|
||||
assertThat(parameters.hasNext(), is(false));
|
||||
}
|
||||
|
||||
/**
|
||||
* @see DATACMNS-134
|
||||
*/
|
||||
@Test
|
||||
public void discoversInnerClassConstructorCorrectly() {
|
||||
|
||||
PersistentEntity<Inner, P> entity = new BasicPersistentEntity<Inner, P>(ClassTypeInformation.from(Inner.class));
|
||||
PreferredConstructorDiscoverer<Inner, P> discoverer = new PreferredConstructorDiscoverer<Inner, P>(entity);
|
||||
PreferredConstructor<Inner, P> constructor = discoverer.getConstructor();
|
||||
|
||||
Parameter<?, P> parameter = constructor.getParameters().iterator().next();
|
||||
assertThat(constructor.isEnclosingClassParameter(parameter), is(true));
|
||||
}
|
||||
|
||||
static class EntityWithoutConstructor {
|
||||
|
||||
}
|
||||
|
||||
static class ClassWithEmptyConstructor {
|
||||
|
||||
public ClassWithEmptyConstructor() {
|
||||
}
|
||||
}
|
||||
|
||||
static class ClassWithMultipleConstructorsAndEmptyOne {
|
||||
|
||||
public ClassWithMultipleConstructorsAndEmptyOne(String value) {
|
||||
}
|
||||
|
||||
public ClassWithMultipleConstructorsAndEmptyOne() {
|
||||
}
|
||||
}
|
||||
|
||||
static class ClassWithMultipleConstructorsWithoutEmptyOne {
|
||||
|
||||
public ClassWithMultipleConstructorsWithoutEmptyOne(String value) {
|
||||
}
|
||||
|
||||
public ClassWithMultipleConstructorsWithoutEmptyOne(Long value) {
|
||||
}
|
||||
}
|
||||
|
||||
static class ClassWithMultipleConstructorsAndAnnotation {
|
||||
|
||||
public ClassWithMultipleConstructorsAndAnnotation() {
|
||||
}
|
||||
|
||||
public ClassWithMultipleConstructorsAndAnnotation(String value) {
|
||||
}
|
||||
|
||||
@PersistenceConstructor
|
||||
public ClassWithMultipleConstructorsAndAnnotation(Long value) {
|
||||
}
|
||||
}
|
||||
|
||||
static class Outer {
|
||||
|
||||
class Inner {
|
||||
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,343 @@
|
||||
/*
|
||||
* Copyright 2011-2012 the original author or authors.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
package org.springframework.data.mapping;
|
||||
|
||||
import static org.hamcrest.Matchers.*;
|
||||
import static org.junit.Assert.*;
|
||||
|
||||
import java.util.Iterator;
|
||||
import java.util.Map;
|
||||
import java.util.Set;
|
||||
|
||||
import org.junit.Rule;
|
||||
import org.junit.Test;
|
||||
import org.junit.rules.ExpectedException;
|
||||
import org.springframework.data.util.ClassTypeInformation;
|
||||
import org.springframework.data.util.TypeInformation;
|
||||
|
||||
/**
|
||||
* Unit tests for {@link PropertyPath}.
|
||||
*
|
||||
* @author Oliver Gierke
|
||||
*/
|
||||
@SuppressWarnings("unused")
|
||||
public class PropertyPathUnitTests {
|
||||
|
||||
@Rule
|
||||
public ExpectedException exception = ExpectedException.none();
|
||||
|
||||
@Test
|
||||
@SuppressWarnings("rawtypes")
|
||||
public void parsesSimplePropertyCorrectly() throws Exception {
|
||||
|
||||
PropertyPath reference = PropertyPath.from("userName", Foo.class);
|
||||
assertThat(reference.hasNext(), is(false));
|
||||
assertThat(reference.toDotPath(), is("userName"));
|
||||
assertThat(reference.getOwningType(), is((TypeInformation) ClassTypeInformation.from(Foo.class)));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void parsesPathPropertyCorrectly() throws Exception {
|
||||
|
||||
PropertyPath reference = PropertyPath.from("userName", Bar.class);
|
||||
assertThat(reference.hasNext(), is(true));
|
||||
assertThat(reference.next(), is(new PropertyPath("name", FooBar.class)));
|
||||
assertThat(reference.toDotPath(), is("user.name"));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void prefersLongerMatches() throws Exception {
|
||||
|
||||
PropertyPath reference = PropertyPath.from("userName", Sample.class);
|
||||
assertThat(reference.hasNext(), is(false));
|
||||
assertThat(reference.toDotPath(), is("userName"));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testname() throws Exception {
|
||||
|
||||
PropertyPath reference = PropertyPath.from("userName", Sample2.class);
|
||||
assertThat(reference.getSegment(), is("user"));
|
||||
assertThat(reference.hasNext(), is(true));
|
||||
assertThat(reference.next(), is(new PropertyPath("name", FooBar.class)));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void prefersExplicitPaths() throws Exception {
|
||||
|
||||
PropertyPath reference = PropertyPath.from("user_name", Sample.class);
|
||||
assertThat(reference.getSegment(), is("user"));
|
||||
assertThat(reference.hasNext(), is(true));
|
||||
assertThat(reference.next(), is(new PropertyPath("name", FooBar.class)));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void handlesGenericsCorrectly() throws Exception {
|
||||
|
||||
PropertyPath reference = PropertyPath.from("usersName", Bar.class);
|
||||
assertThat(reference.getSegment(), is("users"));
|
||||
assertThat(reference.isCollection(), is(true));
|
||||
assertThat(reference.hasNext(), is(true));
|
||||
assertThat(reference.next(), is(new PropertyPath("name", FooBar.class)));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void handlesMapCorrectly() throws Exception {
|
||||
|
||||
PropertyPath reference = PropertyPath.from("userMapName", Bar.class);
|
||||
assertThat(reference.getSegment(), is("userMap"));
|
||||
assertThat(reference.isCollection(), is(false));
|
||||
assertThat(reference.hasNext(), is(true));
|
||||
assertThat(reference.next(), is(new PropertyPath("name", FooBar.class)));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void handlesArrayCorrectly() throws Exception {
|
||||
|
||||
PropertyPath reference = PropertyPath.from("userArrayName", Bar.class);
|
||||
assertThat(reference.getSegment(), is("userArray"));
|
||||
assertThat(reference.isCollection(), is(true));
|
||||
assertThat(reference.hasNext(), is(true));
|
||||
assertThat(reference.next(), is(new PropertyPath("name", FooBar.class)));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void handlesInvalidCollectionCompountTypeProperl() {
|
||||
|
||||
try {
|
||||
PropertyPath.from("usersMame", Bar.class);
|
||||
fail("Expected PropertyReferenceException!");
|
||||
} catch (PropertyReferenceException e) {
|
||||
assertThat(e.getPropertyName(), is("mame"));
|
||||
assertThat(e.getBaseProperty(), is(PropertyPath.from("users", Bar.class)));
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
public void handlesInvalidMapValueTypeProperly() {
|
||||
|
||||
try {
|
||||
PropertyPath.from("userMapMame", Bar.class);
|
||||
fail();
|
||||
} catch (PropertyReferenceException e) {
|
||||
assertThat(e.getPropertyName(), is("mame"));
|
||||
assertThat(e.getBaseProperty(), is(PropertyPath.from("userMap", Bar.class)));
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
public void findsNested() {
|
||||
|
||||
PropertyPath from = PropertyPath.from("barUserName", Sample.class);
|
||||
|
||||
assertThat(from, is(notNullValue()));
|
||||
assertThat(from.getLeafProperty(), is(PropertyPath.from("name", FooBar.class)));
|
||||
}
|
||||
|
||||
/**
|
||||
* @see DATACMNS-45
|
||||
*/
|
||||
@Test
|
||||
public void handlesEmptyUnderscoresCorrectly() {
|
||||
|
||||
PropertyPath propertyPath = PropertyPath.from("_foo", Sample2.class);
|
||||
assertThat(propertyPath.getSegment(), is("_foo"));
|
||||
assertThat(propertyPath.getType(), is(typeCompatibleWith(Foo.class)));
|
||||
|
||||
propertyPath = PropertyPath.from("_foo__email", Sample2.class);
|
||||
assertThat(propertyPath.toDotPath(), is("_foo._email"));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void supportsDotNotationAsWell() {
|
||||
|
||||
PropertyPath propertyPath = PropertyPath.from("bar.userMap.name", Sample.class);
|
||||
|
||||
assertThat(propertyPath, is(notNullValue()));
|
||||
assertThat(propertyPath.getSegment(), is("bar"));
|
||||
assertThat(propertyPath.getLeafProperty(), is(PropertyPath.from("name", FooBar.class)));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void returnsCorrectIteratorForSingleElement() {
|
||||
|
||||
PropertyPath propertyPath = PropertyPath.from("userName", Foo.class);
|
||||
|
||||
Iterator<PropertyPath> iterator = propertyPath.iterator();
|
||||
assertThat(iterator.hasNext(), is(true));
|
||||
assertThat(iterator.next(), is(propertyPath));
|
||||
assertThat(iterator.hasNext(), is(false));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void returnsCorrectIteratorForMultipleElement() {
|
||||
|
||||
PropertyPath propertyPath = PropertyPath.from("user.name", Bar.class);
|
||||
|
||||
Iterator<PropertyPath> iterator = propertyPath.iterator();
|
||||
assertThat(iterator.hasNext(), is(true));
|
||||
assertThat(iterator.next(), is(propertyPath));
|
||||
assertThat(iterator.hasNext(), is(true));
|
||||
assertThat(iterator.next(), is(propertyPath.next()));
|
||||
assertThat(iterator.hasNext(), is(false));
|
||||
}
|
||||
|
||||
/**
|
||||
* @see DATACMNS-139
|
||||
*/
|
||||
@Test
|
||||
public void rejectsInvalidPropertyWithLeadingUnderscore() {
|
||||
try {
|
||||
PropertyPath.from("_id", Foo.class);
|
||||
fail();
|
||||
} catch (PropertyReferenceException e) {
|
||||
assertThat(e.getMessage(), containsString("property _id"));
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* @see DATACMNS-139
|
||||
*/
|
||||
@Test
|
||||
public void rejectsNestedInvalidPropertyWithLeadingUnderscore() {
|
||||
try {
|
||||
PropertyPath.from("_foo_id", Sample2.class);
|
||||
fail();
|
||||
} catch (PropertyReferenceException e) {
|
||||
assertThat(e.getMessage(), containsString("property id"));
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* @see DATACMNS-139
|
||||
*/
|
||||
@Test
|
||||
public void rejectsNestedInvalidPropertyExplictlySplitWithLeadingUnderscore() {
|
||||
try {
|
||||
PropertyPath.from("_foo__id", Sample2.class);
|
||||
fail();
|
||||
} catch (PropertyReferenceException e) {
|
||||
assertThat(e.getMessage(), containsString("property _id"));
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* @see DATACMNS 158
|
||||
*/
|
||||
@Test(expected = PropertyReferenceException.class)
|
||||
public void rejectsInvalidPathsContainingDigits() {
|
||||
PropertyPath.from("PropertyThatWillFail4Sure", Foo.class);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void rejectsInvalidProperty() {
|
||||
|
||||
try {
|
||||
PropertyPath.from("bar", Foo.class);
|
||||
fail();
|
||||
} catch (PropertyReferenceException e) {
|
||||
assertThat(e.getBaseProperty(), is(nullValue()));
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
public void samePathsEqual() {
|
||||
|
||||
PropertyPath left = PropertyPath.from("user.name", Bar.class);
|
||||
PropertyPath right = PropertyPath.from("user.name", Bar.class);
|
||||
|
||||
PropertyPath shortPath = PropertyPath.from("user", Bar.class);
|
||||
|
||||
assertThat(left, is(right));
|
||||
assertThat(right, is(left));
|
||||
assertThat(left, is(not(shortPath)));
|
||||
assertThat(shortPath, is(not(left)));
|
||||
|
||||
assertThat(left, is(not(new Object())));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void hashCodeTests() {
|
||||
|
||||
PropertyPath left = PropertyPath.from("user.name", Bar.class);
|
||||
PropertyPath right = PropertyPath.from("user.name", Bar.class);
|
||||
|
||||
PropertyPath shortPath = PropertyPath.from("user", Bar.class);
|
||||
|
||||
assertThat(left.hashCode(), is(right.hashCode()));
|
||||
assertThat(left.hashCode(), is(not(shortPath.hashCode())));
|
||||
}
|
||||
|
||||
/**
|
||||
* @see DATACMNS-257
|
||||
*/
|
||||
@Test
|
||||
public void findsAllUppercaseProperty() {
|
||||
|
||||
PropertyPath path = PropertyPath.from("UUID", Foo.class);
|
||||
|
||||
assertThat(path, is(notNullValue()));
|
||||
assertThat(path.getSegment(), is("UUID"));
|
||||
}
|
||||
|
||||
/**
|
||||
* @see DATACMNS-257
|
||||
*/
|
||||
@Test
|
||||
public void findsNestedAllUppercaseProperty() {
|
||||
|
||||
PropertyPath path = PropertyPath.from("_fooUUID", Sample2.class);
|
||||
|
||||
assertThat(path, is(notNullValue()));
|
||||
assertThat(path.getSegment(), is("_foo"));
|
||||
assertThat(path.hasNext(), is(true));
|
||||
assertThat(path.next().getSegment(), is("UUID"));
|
||||
}
|
||||
|
||||
private class Foo {
|
||||
|
||||
String userName;
|
||||
String _email;
|
||||
String UUID;
|
||||
}
|
||||
|
||||
private class Bar {
|
||||
|
||||
private FooBar user;
|
||||
private Set<FooBar> users;
|
||||
private Map<String, FooBar> userMap;
|
||||
private FooBar[] userArray;
|
||||
}
|
||||
|
||||
private class FooBar {
|
||||
|
||||
private String name;
|
||||
}
|
||||
|
||||
private class Sample {
|
||||
|
||||
private String userName;
|
||||
private FooBar user;
|
||||
private Bar bar;
|
||||
}
|
||||
|
||||
private class Sample2 {
|
||||
|
||||
private String userNameWhatever;
|
||||
private FooBar user;
|
||||
private Foo _foo;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,126 @@
|
||||
/*
|
||||
* Copyright (c) 2011 by the original author(s).
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
package org.springframework.data.mapping;
|
||||
|
||||
import static org.hamcrest.CoreMatchers.*;
|
||||
import static org.junit.Assert.*;
|
||||
|
||||
import java.util.Collections;
|
||||
import java.util.HashSet;
|
||||
|
||||
import org.junit.Test;
|
||||
import org.springframework.data.mapping.model.SimpleTypeHolder;
|
||||
|
||||
/**
|
||||
* Unit tests for {@link SimpleTypeHolder}.
|
||||
*
|
||||
* @author Oliver Gierke
|
||||
*/
|
||||
public class SimpleTypeHolderUnitTests {
|
||||
|
||||
@Test(expected = IllegalArgumentException.class)
|
||||
public void rejectsNullCustomTypes() {
|
||||
new SimpleTypeHolder(null, false);
|
||||
}
|
||||
|
||||
@Test(expected = IllegalArgumentException.class)
|
||||
public void rejectsNullOriginal() {
|
||||
new SimpleTypeHolder(new HashSet<Class<?>>(), null);
|
||||
}
|
||||
|
||||
/**
|
||||
* @see DATACMNS-31
|
||||
*/
|
||||
@Test(expected = IllegalArgumentException.class)
|
||||
public void rejectsNullTypeForIsSimpleTypeCall() {
|
||||
SimpleTypeHolder holder = new SimpleTypeHolder();
|
||||
holder.isSimpleType(null);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void addsDefaultTypes() {
|
||||
|
||||
SimpleTypeHolder holder = new SimpleTypeHolder();
|
||||
|
||||
assertThat(holder.isSimpleType(String.class), is(true));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void doesNotAddDefaultConvertersIfConfigured() {
|
||||
|
||||
SimpleTypeHolder holder = new SimpleTypeHolder(new HashSet<Class<?>>(), false);
|
||||
|
||||
assertThat(holder.isSimpleType(String.class), is(false));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void addsCustomTypesToSimpleOnes() {
|
||||
|
||||
SimpleTypeHolder holder = new SimpleTypeHolder(Collections.singleton(SimpleTypeHolder.class), true);
|
||||
|
||||
assertThat(holder.isSimpleType(SimpleTypeHolder.class), is(true));
|
||||
assertThat(holder.isSimpleType(SimpleTypeHolderUnitTests.class), is(false));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void createsHolderFromAnotherOneCorrectly() {
|
||||
|
||||
SimpleTypeHolder holder = new SimpleTypeHolder(Collections.singleton(SimpleTypeHolder.class), true);
|
||||
SimpleTypeHolder second = new SimpleTypeHolder(Collections.singleton(SimpleTypeHolderUnitTests.class), holder);
|
||||
|
||||
assertThat(holder.isSimpleType(SimpleTypeHolder.class), is(true));
|
||||
assertThat(holder.isSimpleType(SimpleTypeHolderUnitTests.class), is(false));
|
||||
assertThat(second.isSimpleType(SimpleTypeHolder.class), is(true));
|
||||
assertThat(second.isSimpleType(SimpleTypeHolderUnitTests.class), is(true));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void considersObjectToBeSimpleType() {
|
||||
SimpleTypeHolder holder = new SimpleTypeHolder();
|
||||
assertThat(holder.isSimpleType(Object.class), is(true));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void considersSimpleEnumAsSimple() {
|
||||
|
||||
SimpleTypeHolder holder = new SimpleTypeHolder();
|
||||
assertThat(holder.isSimpleType(SimpleEnum.FOO.getClass()), is(true));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void considersComplexEnumAsSimple() {
|
||||
|
||||
SimpleTypeHolder holder = new SimpleTypeHolder();
|
||||
assertThat(holder.isSimpleType(ComplexEnum.FOO.getClass()), is(true));
|
||||
}
|
||||
|
||||
enum SimpleEnum {
|
||||
|
||||
FOO;
|
||||
}
|
||||
|
||||
enum ComplexEnum {
|
||||
|
||||
FOO {
|
||||
@Override
|
||||
boolean method() {
|
||||
return false;
|
||||
}
|
||||
};
|
||||
|
||||
abstract boolean method();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,111 @@
|
||||
/*
|
||||
* Copyright (c) 2011 by the original author(s).
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
package org.springframework.data.mapping.context;
|
||||
|
||||
import static org.mockito.Mockito.*;
|
||||
|
||||
import java.beans.PropertyDescriptor;
|
||||
import java.lang.reflect.Field;
|
||||
import java.util.Collections;
|
||||
|
||||
import org.junit.Test;
|
||||
import org.springframework.data.mapping.PersistentEntity;
|
||||
import org.springframework.data.mapping.PersistentProperty;
|
||||
import org.springframework.data.mapping.PropertyHandler;
|
||||
import org.springframework.data.mapping.model.BasicPersistentEntity;
|
||||
import org.springframework.data.mapping.model.SimpleTypeHolder;
|
||||
import org.springframework.data.util.TypeInformation;
|
||||
|
||||
/**
|
||||
* Integration tests for {@link AbstractMappingContext}.
|
||||
*
|
||||
* @author Oliver Gierke
|
||||
*/
|
||||
public class AbstractMappingContextIntegrationTests<T extends PersistentProperty<T>> {
|
||||
|
||||
@Test
|
||||
public void foo() throws InterruptedException {
|
||||
|
||||
final DummyMappingContext context = new DummyMappingContext();
|
||||
|
||||
Thread a = new Thread(new Runnable() {
|
||||
public void run() {
|
||||
context.getPersistentEntity(Person.class);
|
||||
}
|
||||
});
|
||||
|
||||
Thread b = new Thread(new Runnable() {
|
||||
|
||||
public void run() {
|
||||
|
||||
PersistentEntity<Object, T> entity = context.getPersistentEntity(Person.class);
|
||||
|
||||
entity.doWithProperties(new PropertyHandler<T>() {
|
||||
public void doWithPersistentProperty(T persistentProperty) {
|
||||
try {
|
||||
Thread.sleep(1000);
|
||||
} catch (InterruptedException e) {
|
||||
throw new RuntimeException(e);
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
});
|
||||
|
||||
a.start();
|
||||
Thread.sleep(2800);
|
||||
b.start();
|
||||
|
||||
a.join();
|
||||
b.join();
|
||||
}
|
||||
|
||||
class DummyMappingContext extends AbstractMappingContext<BasicPersistentEntity<Object, T>, T> {
|
||||
|
||||
@Override
|
||||
@SuppressWarnings("unchecked")
|
||||
protected <S> BasicPersistentEntity<Object, T> createPersistentEntity(TypeInformation<S> typeInformation) {
|
||||
return (BasicPersistentEntity<Object, T>) new BasicPersistentEntity<S, T>(typeInformation);
|
||||
}
|
||||
|
||||
@Override
|
||||
@SuppressWarnings({ "rawtypes", "unchecked" })
|
||||
protected T createPersistentProperty(final Field field, final PropertyDescriptor descriptor,
|
||||
final BasicPersistentEntity<Object, T> owner, final SimpleTypeHolder simpleTypeHolder) {
|
||||
|
||||
PersistentProperty prop = mock(PersistentProperty.class);
|
||||
|
||||
when(prop.getTypeInformation()).thenReturn((TypeInformation) owner.getTypeInformation());
|
||||
when(prop.getName()).thenReturn(field.getName());
|
||||
when(prop.getPersistentEntityType()).thenReturn(Collections.EMPTY_SET);
|
||||
|
||||
try {
|
||||
Thread.sleep(800);
|
||||
} catch (InterruptedException e) {
|
||||
throw new RuntimeException(e);
|
||||
}
|
||||
|
||||
return (T) prop;
|
||||
}
|
||||
}
|
||||
|
||||
class Person {
|
||||
|
||||
String firstname;
|
||||
String lastname;
|
||||
String email;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,158 @@
|
||||
/*
|
||||
* Copyright 2011-2012 the original author or authors.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
package org.springframework.data.mapping.context;
|
||||
|
||||
import static org.hamcrest.Matchers.*;
|
||||
import static org.junit.Assert.*;
|
||||
import static org.mockito.Mockito.*;
|
||||
import groovy.lang.MetaClass;
|
||||
|
||||
import java.util.Collections;
|
||||
|
||||
import org.junit.Before;
|
||||
import org.junit.Test;
|
||||
import org.mockito.Mockito;
|
||||
import org.springframework.context.ApplicationContext;
|
||||
import org.springframework.context.ApplicationEvent;
|
||||
import org.springframework.context.event.ContextRefreshedEvent;
|
||||
import org.springframework.data.mapping.PersistentEntity;
|
||||
import org.springframework.data.mapping.PropertyPath;
|
||||
import org.springframework.data.mapping.model.BasicPersistentEntity;
|
||||
import org.springframework.data.mapping.model.MappingException;
|
||||
import org.springframework.data.mapping.model.SimpleTypeHolder;
|
||||
import org.springframework.data.util.TypeInformation;
|
||||
|
||||
/**
|
||||
* Unit test for {@link AbstractMappingContext}.
|
||||
*
|
||||
* @author Oliver Gierke
|
||||
*/
|
||||
public class AbstractMappingContextUnitTests {
|
||||
|
||||
final SimpleTypeHolder holder = new SimpleTypeHolder();
|
||||
SampleMappingContext context;
|
||||
|
||||
@Before
|
||||
public void setUp() {
|
||||
context = new SampleMappingContext();
|
||||
context.setSimpleTypeHolder(holder);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void doesNotTryToLookupPersistentEntityForLeafProperty() {
|
||||
PersistentPropertyPath<SamplePersistentProperty> path = context.getPersistentPropertyPath(PropertyPath.from("name",
|
||||
Person.class));
|
||||
assertThat(path, is(notNullValue()));
|
||||
}
|
||||
|
||||
/**
|
||||
* @see DATACMNS-92
|
||||
*/
|
||||
@Test(expected = MappingException.class)
|
||||
public void doesNotAddInvalidEntity() {
|
||||
|
||||
context = new SampleMappingContext() {
|
||||
@Override
|
||||
@SuppressWarnings("unchecked")
|
||||
protected <S> BasicPersistentEntity<Object, SamplePersistentProperty> createPersistentEntity(
|
||||
TypeInformation<S> typeInformation) {
|
||||
return new BasicPersistentEntity<Object, SamplePersistentProperty>((TypeInformation<Object>) typeInformation) {
|
||||
@Override
|
||||
public void verify() {
|
||||
if (Unsupported.class.isAssignableFrom(getType())) {
|
||||
throw new MappingException("Unsupported type!");
|
||||
}
|
||||
}
|
||||
};
|
||||
}
|
||||
};
|
||||
|
||||
try {
|
||||
context.getPersistentEntity(Unsupported.class);
|
||||
} catch (MappingException e) {
|
||||
// expected
|
||||
}
|
||||
|
||||
context.getPersistentEntity(Unsupported.class);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void registersEntitiesOnContextRefreshedEvent() {
|
||||
|
||||
ApplicationContext context = mock(ApplicationContext.class);
|
||||
|
||||
SampleMappingContext mappingContext = new SampleMappingContext();
|
||||
mappingContext.setInitialEntitySet(Collections.singleton(Person.class));
|
||||
mappingContext.setApplicationContext(context);
|
||||
|
||||
verify(context, times(0)).publishEvent(Mockito.any(ApplicationEvent.class));
|
||||
|
||||
mappingContext.onApplicationEvent(new ContextRefreshedEvent(context));
|
||||
verify(context, times(1)).publishEvent(Mockito.any(ApplicationEvent.class));
|
||||
}
|
||||
|
||||
/**
|
||||
* @see DATACMNS-214
|
||||
*/
|
||||
@Test
|
||||
public void returnsNullPersistentEntityForSimpleTypes() {
|
||||
|
||||
SampleMappingContext context = new SampleMappingContext();
|
||||
assertThat(context.getPersistentEntity(String.class), is(nullValue()));
|
||||
}
|
||||
|
||||
/**
|
||||
* @see DATACMNS-214
|
||||
*/
|
||||
@Test(expected = IllegalArgumentException.class)
|
||||
public void rejectsNullValueForGetPersistentEntityOfClass() {
|
||||
context.getPersistentEntity((Class<?>) null);
|
||||
}
|
||||
|
||||
/**
|
||||
* @see DATACMNS-214
|
||||
*/
|
||||
@Test(expected = IllegalArgumentException.class)
|
||||
public void rejectsNullValueForGetPersistentEntityOfTypeInformation() {
|
||||
context.getPersistentEntity((TypeInformation<?>) null);
|
||||
}
|
||||
|
||||
/**
|
||||
* @see DATACMNS-228
|
||||
*/
|
||||
@Test
|
||||
public void doesNotCreatePersistentPropertyForGroovyMetaClass() {
|
||||
|
||||
SampleMappingContext mappingContext = new SampleMappingContext();
|
||||
mappingContext.initialize();
|
||||
|
||||
PersistentEntity<Object, SamplePersistentProperty> entity = mappingContext.getPersistentEntity(Sample.class);
|
||||
assertThat(entity.getPersistentProperty("metaClass"), is(nullValue()));
|
||||
}
|
||||
|
||||
class Person {
|
||||
String name;
|
||||
}
|
||||
|
||||
class Unsupported {
|
||||
|
||||
}
|
||||
|
||||
class Sample {
|
||||
|
||||
MetaClass metaClass;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,124 @@
|
||||
/*
|
||||
* Copyright 2011 the original author or authors.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
package org.springframework.data.mapping.context;
|
||||
|
||||
import static org.hamcrest.CoreMatchers.*;
|
||||
import static org.junit.Assert.*;
|
||||
import static org.mockito.Matchers.*;
|
||||
import static org.mockito.Mockito.*;
|
||||
|
||||
import java.util.Arrays;
|
||||
|
||||
import org.junit.Before;
|
||||
import org.junit.Test;
|
||||
import org.junit.runner.RunWith;
|
||||
import org.mockito.Mock;
|
||||
import org.mockito.runners.MockitoJUnitRunner;
|
||||
import org.springframework.core.convert.converter.Converter;
|
||||
import org.springframework.data.mapping.PersistentProperty;
|
||||
|
||||
/**
|
||||
* Unit tests for {@link DefaultPersistentPropertyPath}.
|
||||
*
|
||||
* @author Oliver Gierke
|
||||
*/
|
||||
@RunWith(MockitoJUnitRunner.class)
|
||||
public class DefaultPersistenPropertyPathUnitTests<T extends PersistentProperty<T>> {
|
||||
|
||||
@Mock
|
||||
T first, second;
|
||||
|
||||
@Mock
|
||||
Converter<T, String> converter;
|
||||
|
||||
PersistentPropertyPath<T> oneLeg;
|
||||
PersistentPropertyPath<T> twoLegs;
|
||||
|
||||
@Before
|
||||
@SuppressWarnings("unchecked")
|
||||
public void setUp() {
|
||||
oneLeg = new DefaultPersistentPropertyPath<T>(Arrays.asList(first));
|
||||
twoLegs = new DefaultPersistentPropertyPath<T>(Arrays.asList(first, second));
|
||||
}
|
||||
|
||||
@Test(expected = IllegalArgumentException.class)
|
||||
public void rejectsNullProperties() {
|
||||
new DefaultPersistentPropertyPath<T>(null);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void usesPropertyNameForSimpleDotPath() {
|
||||
|
||||
when(first.getName()).thenReturn("foo");
|
||||
when(second.getName()).thenReturn("bar");
|
||||
|
||||
assertThat(twoLegs.toDotPath(), is("foo.bar"));
|
||||
}
|
||||
|
||||
@Test
|
||||
@SuppressWarnings("unchecked")
|
||||
public void usesConverterToCreatePropertyPath() {
|
||||
|
||||
when(converter.convert((T) any())).thenReturn("foo");
|
||||
|
||||
assertThat(twoLegs.toDotPath(converter), is("foo.foo"));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void returnsCorrectLeafProperty() {
|
||||
|
||||
assertThat(twoLegs.getLeafProperty(), is(second));
|
||||
assertThat(oneLeg.getLeafProperty(), is(first));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void returnsCorrectBaseProperty() {
|
||||
|
||||
assertThat(twoLegs.getBaseProperty(), is(first));
|
||||
assertThat(oneLeg.getBaseProperty(), is(first));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void detectsBasePathCorrectly() {
|
||||
|
||||
assertThat(oneLeg.isBasePathOf(twoLegs), is(true));
|
||||
assertThat(twoLegs.isBasePathOf(oneLeg), is(false));
|
||||
}
|
||||
|
||||
@Test
|
||||
@SuppressWarnings("unchecked")
|
||||
public void calculatesExtensionCorrectly() {
|
||||
|
||||
PersistentPropertyPath<T> extension = twoLegs.getExtensionForBaseOf(oneLeg);
|
||||
assertThat(extension, is((PersistentPropertyPath<T>) new DefaultPersistentPropertyPath<T>(Arrays.asList(second))));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void returnsTheCorrectParentPath() {
|
||||
assertThat(twoLegs.getParentPath(), is(oneLeg));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void returnsItselfAsParentPathIfSizeOne() {
|
||||
assertThat(oneLeg.getParentPath(), is(oneLeg));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void pathReturnsCorrectSize() {
|
||||
assertThat(oneLeg.getLength(), is(1));
|
||||
assertThat(twoLegs.getLength(), is(2));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,80 @@
|
||||
/*
|
||||
* Copyright 2012 the original author or authors.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
package org.springframework.data.mapping.context;
|
||||
|
||||
import static org.hamcrest.CoreMatchers.*;
|
||||
import static org.junit.Assert.*;
|
||||
|
||||
import org.junit.Test;
|
||||
import org.springframework.data.mapping.context.AbstractMappingContext.FieldMatch;
|
||||
|
||||
/**
|
||||
* Unit tests for {@link FieldMatch}. Introduced for DATACMNS-228.
|
||||
*
|
||||
* @since 1.4
|
||||
* @author Oliver Gierke
|
||||
*/
|
||||
public class FieldMatchUnitTests {
|
||||
|
||||
@Test(expected = IllegalArgumentException.class)
|
||||
public void rejectsBothParametersBeingNull() {
|
||||
|
||||
new FieldMatch(null, null);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void matchesFieldByConcreteNameAndType() throws Exception {
|
||||
|
||||
FieldMatch match = new FieldMatch("name", "java.lang.String");
|
||||
assertThat(match.matches(Sample.class.getField("this$0")), is(false));
|
||||
assertThat(match.matches(Sample.class.getField("this$1")), is(false));
|
||||
assertThat(match.matches(Sample.class.getField("name")), is(true));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void matchesFieldByNamePattern() throws Exception {
|
||||
|
||||
FieldMatch match = new FieldMatch("this\\$.*", "java.lang.Object");
|
||||
assertThat(match.matches(Sample.class.getField("this$0")), is(true));
|
||||
assertThat(match.matches(Sample.class.getField("this$1")), is(true));
|
||||
assertThat(match.matches(Sample.class.getField("name")), is(false));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void matchesFieldByNameOnly() throws Exception {
|
||||
|
||||
FieldMatch match = new FieldMatch("this\\$.*", null);
|
||||
assertThat(match.matches(Sample.class.getField("this$0")), is(true));
|
||||
assertThat(match.matches(Sample.class.getField("this$1")), is(true));
|
||||
assertThat(match.matches(Sample.class.getField("name")), is(false));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void matchesFieldByTypeNameOnly() throws Exception {
|
||||
|
||||
FieldMatch match = new FieldMatch(null, "java.lang.Object");
|
||||
assertThat(match.matches(Sample.class.getField("this$0")), is(true));
|
||||
assertThat(match.matches(Sample.class.getField("this$1")), is(true));
|
||||
assertThat(match.matches(Sample.class.getField("name")), is(false));
|
||||
}
|
||||
|
||||
static class Sample {
|
||||
|
||||
public Object this$0;
|
||||
public Object this$1;
|
||||
public String name;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,65 @@
|
||||
/*
|
||||
* Copyright 2012 the original author or authors.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
package org.springframework.data.mapping.context;
|
||||
|
||||
import static org.hamcrest.CoreMatchers.*;
|
||||
import static org.junit.Assert.*;
|
||||
|
||||
import org.junit.Test;
|
||||
import org.junit.runner.RunWith;
|
||||
import org.mockito.Mock;
|
||||
import org.mockito.runners.MockitoJUnitRunner;
|
||||
import org.springframework.data.mapping.PersistentEntity;
|
||||
import org.springframework.data.mapping.PersistentProperty;
|
||||
import org.springframework.data.mapping.context.MappingContext;
|
||||
import org.springframework.data.mapping.context.MappingContextEvent;
|
||||
|
||||
/**
|
||||
* Unit tests for {@link MappingContextEvent}.
|
||||
*
|
||||
* @author Oliver Gierke
|
||||
*/
|
||||
@RunWith(MockitoJUnitRunner.class)
|
||||
public class MappingContextEventUnitTests<E extends PersistentEntity<?, P>, P extends PersistentProperty<P>> {
|
||||
|
||||
@Mock
|
||||
E entity;
|
||||
|
||||
@Mock
|
||||
MappingContext<?, ?> mappingContext, otherMappingContext;
|
||||
|
||||
@Test
|
||||
public void returnsPersistentEntityHandedToTheEvent() {
|
||||
|
||||
MappingContextEvent<E, P> event = new MappingContextEvent<E, P>(mappingContext, entity);
|
||||
assertThat(event.getPersistentEntity(), is(entity));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void usesMappingContextAsEventSource() {
|
||||
|
||||
MappingContextEvent<E, P> event = new MappingContextEvent<E, P>(mappingContext, entity);
|
||||
assertThat(event.getSource(), is((Object) mappingContext));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void detectsEmittingMappingContextCorrectly() {
|
||||
|
||||
MappingContextEvent<E, P> event = new MappingContextEvent<E, P>(mappingContext, entity);
|
||||
assertThat(event.wasEmittedBy(mappingContext), is(true));
|
||||
assertThat(event.wasEmittedBy(otherMappingContext), is(false));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,26 @@
|
||||
package org.springframework.data.mapping.context;
|
||||
|
||||
import java.beans.PropertyDescriptor;
|
||||
import java.lang.reflect.Field;
|
||||
|
||||
import org.springframework.data.mapping.model.BasicPersistentEntity;
|
||||
import org.springframework.data.mapping.model.SimpleTypeHolder;
|
||||
import org.springframework.data.util.TypeInformation;
|
||||
|
||||
class SampleMappingContext extends
|
||||
AbstractMappingContext<BasicPersistentEntity<Object, SamplePersistentProperty>, SamplePersistentProperty> {
|
||||
|
||||
@Override
|
||||
@SuppressWarnings("unchecked")
|
||||
protected <S> BasicPersistentEntity<Object, SamplePersistentProperty> createPersistentEntity(
|
||||
TypeInformation<S> typeInformation) {
|
||||
return new BasicPersistentEntity<Object, SamplePersistentProperty>((TypeInformation<Object>) typeInformation);
|
||||
}
|
||||
|
||||
@Override
|
||||
protected SamplePersistentProperty createPersistentProperty(final Field field, final PropertyDescriptor descriptor,
|
||||
final BasicPersistentEntity<Object, SamplePersistentProperty> owner, final SimpleTypeHolder simpleTypeHolder) {
|
||||
|
||||
return new SamplePersistentProperty(field, descriptor, owner, simpleTypeHolder);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,37 @@
|
||||
/*
|
||||
* Copyright 2012 the original author or authors.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
package org.springframework.data.mapping.context;
|
||||
|
||||
import java.beans.PropertyDescriptor;
|
||||
import java.lang.reflect.Field;
|
||||
|
||||
import org.springframework.data.mapping.Association;
|
||||
import org.springframework.data.mapping.model.AnnotationBasedPersistentProperty;
|
||||
import org.springframework.data.mapping.model.BasicPersistentEntity;
|
||||
import org.springframework.data.mapping.model.SimpleTypeHolder;
|
||||
|
||||
class SamplePersistentProperty extends AnnotationBasedPersistentProperty<SamplePersistentProperty> {
|
||||
|
||||
public SamplePersistentProperty(Field field, PropertyDescriptor propertyDescriptor,
|
||||
BasicPersistentEntity<?, SamplePersistentProperty> owner, SimpleTypeHolder simpleTypeHolder) {
|
||||
super(field, propertyDescriptor, owner, simpleTypeHolder);
|
||||
}
|
||||
|
||||
@Override
|
||||
protected Association<SamplePersistentProperty> createAssociation() {
|
||||
return new Association<SamplePersistentProperty>(this, null);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,302 @@
|
||||
/*
|
||||
* Copyright 2011-2012 the original author or authors.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
package org.springframework.data.mapping.model;
|
||||
|
||||
import static org.hamcrest.Matchers.*;
|
||||
import static org.junit.Assert.*;
|
||||
|
||||
import java.beans.BeanInfo;
|
||||
import java.beans.IntrospectionException;
|
||||
import java.beans.Introspector;
|
||||
import java.beans.PropertyDescriptor;
|
||||
import java.lang.reflect.Field;
|
||||
import java.util.Collection;
|
||||
import java.util.Map;
|
||||
import java.util.TreeSet;
|
||||
|
||||
import org.junit.Before;
|
||||
import org.junit.Test;
|
||||
import org.springframework.data.mapping.Association;
|
||||
import org.springframework.data.mapping.PersistentEntity;
|
||||
import org.springframework.data.mapping.PersistentProperty;
|
||||
import org.springframework.data.util.ClassTypeInformation;
|
||||
import org.springframework.data.util.TypeInformation;
|
||||
import org.springframework.util.ReflectionUtils;
|
||||
|
||||
/**
|
||||
* Unit tests for {@link AbstractPersistentProperty}.
|
||||
*
|
||||
* @author Oliver Gierke
|
||||
*/
|
||||
public class AbstractPersistentPropertyUnitTests {
|
||||
|
||||
TypeInformation<TestClassComplex> typeInfo;
|
||||
PersistentEntity<TestClassComplex, SamplePersistentProperty> entity;
|
||||
SimpleTypeHolder typeHolder;
|
||||
|
||||
@Before
|
||||
public void setUp() {
|
||||
typeInfo = ClassTypeInformation.from(TestClassComplex.class);
|
||||
entity = new BasicPersistentEntity<TestClassComplex, SamplePersistentProperty>(typeInfo);
|
||||
typeHolder = new SimpleTypeHolder();
|
||||
}
|
||||
|
||||
/**
|
||||
* @see DATACMNS-68
|
||||
*/
|
||||
@Test
|
||||
public void discoversComponentTypeCorrectly() throws Exception {
|
||||
|
||||
Field field = ReflectionUtils.findField(TestClassComplex.class, "testClassSet");
|
||||
|
||||
SamplePersistentProperty property = new SamplePersistentProperty(field, null, entity, typeHolder);
|
||||
property.getComponentType();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void returnsNestedEntityTypeCorrectly() {
|
||||
|
||||
Field field = ReflectionUtils.findField(TestClassComplex.class, "testClassSet");
|
||||
|
||||
SamplePersistentProperty property = new SamplePersistentProperty(field, null, entity, typeHolder);
|
||||
assertThat(property.getPersistentEntityType().iterator().hasNext(), is(false));
|
||||
}
|
||||
|
||||
/**
|
||||
* @see DATACMNS-132
|
||||
*/
|
||||
@Test
|
||||
public void isEntityWorksForUntypedMaps() throws Exception {
|
||||
|
||||
Field field = ReflectionUtils.findField(TestClassComplex.class, "map");
|
||||
SamplePersistentProperty property = new SamplePersistentProperty(field, null, entity, typeHolder);
|
||||
assertThat(property.isEntity(), is(false));
|
||||
}
|
||||
|
||||
/**
|
||||
* @see DATACMNS-132
|
||||
*/
|
||||
@Test
|
||||
public void isEntityWorksForUntypedCollection() throws Exception {
|
||||
|
||||
Field field = ReflectionUtils.findField(TestClassComplex.class, "collection");
|
||||
SamplePersistentProperty property = new SamplePersistentProperty(field, null, entity, typeHolder);
|
||||
assertThat(property.isEntity(), is(false));
|
||||
}
|
||||
|
||||
/**
|
||||
* @see DATACMNS-121
|
||||
*/
|
||||
@Test
|
||||
public void considersPropertiesEqualIfFieldEquals() {
|
||||
|
||||
Field first = ReflectionUtils.findField(FirstConcrete.class, "genericField");
|
||||
Field second = ReflectionUtils.findField(SecondConcrete.class, "genericField");
|
||||
|
||||
SamplePersistentProperty firstProperty = new SamplePersistentProperty(first, null, entity, typeHolder);
|
||||
SamplePersistentProperty secondProperty = new SamplePersistentProperty(second, null, entity, typeHolder);
|
||||
|
||||
assertThat(firstProperty, is(secondProperty));
|
||||
assertThat(firstProperty.hashCode(), is(secondProperty.hashCode()));
|
||||
}
|
||||
|
||||
/**
|
||||
* @see DATACMNS-180
|
||||
*/
|
||||
@Test
|
||||
public void doesNotConsiderJavaTransientFieldsTransient() {
|
||||
|
||||
Field transientField = ReflectionUtils.findField(TestClassComplex.class, "transientField");
|
||||
|
||||
PersistentProperty<?> property = new SamplePersistentProperty(transientField, null, entity, typeHolder);
|
||||
assertThat(property.isTransient(), is(false));
|
||||
}
|
||||
|
||||
/**
|
||||
* @see DATACMNS-206
|
||||
*/
|
||||
@Test
|
||||
public void findsSimpleGettersAndASetters() {
|
||||
|
||||
Field field = ReflectionUtils.findField(AccessorTestClass.class, "id");
|
||||
PersistentProperty<SamplePersistentProperty> property = new SamplePersistentProperty(field, getPropertyDescriptor(
|
||||
AccessorTestClass.class, "id"), entity, typeHolder);
|
||||
|
||||
assertThat(property.getGetter(), is(notNullValue()));
|
||||
assertThat(property.getSetter(), is(notNullValue()));
|
||||
}
|
||||
|
||||
/**
|
||||
* @see DATACMNS-206
|
||||
*/
|
||||
@Test
|
||||
public void doesNotUseInvalidGettersAndASetters() {
|
||||
|
||||
Field field = ReflectionUtils.findField(AccessorTestClass.class, "anotherId");
|
||||
PersistentProperty<SamplePersistentProperty> property = new SamplePersistentProperty(field, getPropertyDescriptor(
|
||||
AccessorTestClass.class, "anotherId"), entity, typeHolder);
|
||||
|
||||
assertThat(property.getGetter(), is(nullValue()));
|
||||
assertThat(property.getSetter(), is(nullValue()));
|
||||
}
|
||||
|
||||
/**
|
||||
* @see DATACMNS-206
|
||||
*/
|
||||
@Test
|
||||
public void usesCustomGetter() {
|
||||
|
||||
Field field = ReflectionUtils.findField(AccessorTestClass.class, "yetAnotherId");
|
||||
PersistentProperty<SamplePersistentProperty> property = new SamplePersistentProperty(field, getPropertyDescriptor(
|
||||
AccessorTestClass.class, "yetAnotherId"), entity, typeHolder);
|
||||
|
||||
assertThat(property.getGetter(), is(notNullValue()));
|
||||
assertThat(property.getSetter(), is(nullValue()));
|
||||
}
|
||||
|
||||
/**
|
||||
* @see DATACMNS-206
|
||||
*/
|
||||
@Test
|
||||
public void usesCustomSetter() {
|
||||
|
||||
Field field = ReflectionUtils.findField(AccessorTestClass.class, "yetYetAnotherId");
|
||||
PersistentProperty<SamplePersistentProperty> property = new SamplePersistentProperty(field, getPropertyDescriptor(
|
||||
AccessorTestClass.class, "yetYetAnotherId"), entity, typeHolder);
|
||||
|
||||
assertThat(property.getGetter(), is(nullValue()));
|
||||
assertThat(property.getSetter(), is(notNullValue()));
|
||||
}
|
||||
|
||||
/**
|
||||
* @see DATACMNS-206
|
||||
*/
|
||||
@Test
|
||||
public void returnsNullGetterAndSetterIfNoPropertyDescriptorGiven() {
|
||||
|
||||
Field field = ReflectionUtils.findField(AccessorTestClass.class, "id");
|
||||
PersistentProperty<SamplePersistentProperty> property = new SamplePersistentProperty(field, null, entity,
|
||||
typeHolder);
|
||||
|
||||
assertThat(property.getGetter(), is(nullValue()));
|
||||
assertThat(property.getSetter(), is(nullValue()));
|
||||
}
|
||||
|
||||
private static PropertyDescriptor getPropertyDescriptor(Class<?> type, String propertyName) {
|
||||
|
||||
try {
|
||||
|
||||
BeanInfo info = Introspector.getBeanInfo(type);
|
||||
|
||||
for (PropertyDescriptor descriptor : info.getPropertyDescriptors()) {
|
||||
if (descriptor.getName().equals(propertyName)) {
|
||||
return descriptor;
|
||||
}
|
||||
}
|
||||
|
||||
return null;
|
||||
|
||||
} catch (IntrospectionException e) {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
class Generic<T> {
|
||||
T genericField;
|
||||
|
||||
}
|
||||
|
||||
class FirstConcrete extends Generic<String> {
|
||||
|
||||
}
|
||||
|
||||
class SecondConcrete extends Generic<Integer> {
|
||||
|
||||
}
|
||||
|
||||
@SuppressWarnings("serial")
|
||||
class TestClassSet extends TreeSet<Object> {
|
||||
}
|
||||
|
||||
@SuppressWarnings("rawtypes")
|
||||
class TestClassComplex {
|
||||
|
||||
String id;
|
||||
TestClassSet testClassSet;
|
||||
Map map;
|
||||
Collection collection;
|
||||
transient Object transientField;
|
||||
}
|
||||
|
||||
class AccessorTestClass {
|
||||
|
||||
// Valid getters and setters
|
||||
Long id;
|
||||
// Invalid getters and setters
|
||||
Long anotherId;
|
||||
|
||||
// Customized getter
|
||||
Number yetAnotherId;
|
||||
|
||||
// Customized setter
|
||||
Number yetYetAnotherId;
|
||||
|
||||
public Long getId() {
|
||||
return id;
|
||||
}
|
||||
|
||||
public void setId(Long id) {
|
||||
this.id = id;
|
||||
}
|
||||
|
||||
public String getAnotherId() {
|
||||
return anotherId.toString();
|
||||
}
|
||||
|
||||
public void setAnotherId(String anotherId) {
|
||||
this.anotherId = Long.parseLong(anotherId);
|
||||
}
|
||||
|
||||
public Long getYetAnotherId() {
|
||||
return null;
|
||||
}
|
||||
|
||||
public void setYetYetAnotherId(Object yetYetAnotherId) {
|
||||
this.yetYetAnotherId = null;
|
||||
}
|
||||
}
|
||||
|
||||
class SamplePersistentProperty extends AbstractPersistentProperty<SamplePersistentProperty> {
|
||||
|
||||
public SamplePersistentProperty(Field field, PropertyDescriptor propertyDescriptor,
|
||||
PersistentEntity<?, SamplePersistentProperty> owner, SimpleTypeHolder simpleTypeHolder) {
|
||||
super(field, propertyDescriptor, owner, simpleTypeHolder);
|
||||
}
|
||||
|
||||
public boolean isIdProperty() {
|
||||
return false;
|
||||
}
|
||||
|
||||
public boolean isVersionProperty() {
|
||||
return false;
|
||||
}
|
||||
|
||||
@Override
|
||||
protected Association<SamplePersistentProperty> createAssociation() {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,146 @@
|
||||
package org.springframework.data.mapping.model;
|
||||
|
||||
import static org.hamcrest.CoreMatchers.*;
|
||||
import static org.junit.Assert.*;
|
||||
import static org.mockito.Mockito.*;
|
||||
|
||||
import java.util.Comparator;
|
||||
import java.util.Iterator;
|
||||
import java.util.SortedSet;
|
||||
|
||||
import org.junit.Test;
|
||||
import org.junit.runner.RunWith;
|
||||
import org.mockito.Mock;
|
||||
import org.mockito.Mockito;
|
||||
import org.mockito.runners.MockitoJUnitRunner;
|
||||
import org.springframework.data.annotation.TypeAlias;
|
||||
import org.springframework.data.mapping.PersistentEntity;
|
||||
import org.springframework.data.mapping.PersistentEntitySpec;
|
||||
import org.springframework.data.mapping.PersistentProperty;
|
||||
import org.springframework.data.mapping.Person;
|
||||
import org.springframework.data.util.ClassTypeInformation;
|
||||
import org.springframework.test.util.ReflectionTestUtils;
|
||||
|
||||
/**
|
||||
* Unit test for {@link BasicPersistentEntity}.
|
||||
*
|
||||
* @author Oliver Gierke
|
||||
*/
|
||||
@RunWith(MockitoJUnitRunner.class)
|
||||
public class BasicPersistentEntityUnitTests<T extends PersistentProperty<T>> {
|
||||
|
||||
@Mock
|
||||
T property;
|
||||
|
||||
@Test
|
||||
public void assertInvariants() {
|
||||
PersistentEntitySpec.assertInvariants(createEntity(null));
|
||||
}
|
||||
|
||||
@Test(expected = IllegalArgumentException.class)
|
||||
public void rejectsNullTypeInformation() {
|
||||
new BasicPersistentEntity<Object, T>(null);
|
||||
}
|
||||
|
||||
@Test(expected = IllegalArgumentException.class)
|
||||
public void rejectsNullProperty() {
|
||||
createEntity(null).addPersistentProperty(null);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void returnsNullForTypeAliasIfNoneConfigured() {
|
||||
|
||||
PersistentEntity<Entity, T> entity = new BasicPersistentEntity<Entity, T>(ClassTypeInformation.from(Entity.class));
|
||||
assertThat(entity.getTypeAlias(), is(nullValue()));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void returnsTypeAliasIfAnnotated() {
|
||||
|
||||
PersistentEntity<AliasedEntity, T> entity = new BasicPersistentEntity<AliasedEntity, T>(
|
||||
ClassTypeInformation.from(AliasedEntity.class));
|
||||
assertThat(entity.getTypeAlias(), is((Object) "foo"));
|
||||
}
|
||||
|
||||
/**
|
||||
* @see DATACMNS-50
|
||||
*/
|
||||
@Test
|
||||
@SuppressWarnings("unchecked")
|
||||
public void considersComparatorForPropertyOrder() {
|
||||
|
||||
BasicPersistentEntity<Person, T> entity = createEntity(new Comparator<T>() {
|
||||
public int compare(T o1, T o2) {
|
||||
return o1.getName().compareTo(o2.getName());
|
||||
}
|
||||
});
|
||||
|
||||
T lastName = (T) Mockito.mock(PersistentProperty.class);
|
||||
when(lastName.getName()).thenReturn("lastName");
|
||||
|
||||
T firstName = (T) Mockito.mock(PersistentProperty.class);
|
||||
when(firstName.getName()).thenReturn("firstName");
|
||||
|
||||
T ssn = (T) Mockito.mock(PersistentProperty.class);
|
||||
when(ssn.getName()).thenReturn("ssn");
|
||||
|
||||
entity.addPersistentProperty(lastName);
|
||||
entity.addPersistentProperty(firstName);
|
||||
entity.addPersistentProperty(ssn);
|
||||
|
||||
SortedSet<T> properties = (SortedSet<T>) ReflectionTestUtils.getField(entity, "properties");
|
||||
|
||||
assertThat(properties.size(), is(3));
|
||||
Iterator<T> iterator = properties.iterator();
|
||||
assertThat(iterator.next(), is(entity.getPersistentProperty("firstName")));
|
||||
assertThat(iterator.next(), is(entity.getPersistentProperty("lastName")));
|
||||
assertThat(iterator.next(), is(entity.getPersistentProperty("ssn")));
|
||||
}
|
||||
|
||||
/**
|
||||
* @see DATACMNS-186
|
||||
*/
|
||||
@Test
|
||||
public void addingAndIdPropertySetsIdPropertyInternally() {
|
||||
|
||||
MutablePersistentEntity<Person, T> entity = createEntity(null);
|
||||
assertThat(entity.getIdProperty(), is(nullValue()));
|
||||
|
||||
when(property.isIdProperty()).thenReturn(true);
|
||||
entity.addPersistentProperty(property);
|
||||
assertThat(entity.getIdProperty(), is(property));
|
||||
}
|
||||
|
||||
/**
|
||||
* @see DATACMNS-186
|
||||
*/
|
||||
@Test
|
||||
public void rejectsIdPropertyIfAlreadySet() {
|
||||
|
||||
MutablePersistentEntity<Person, T> entity = createEntity(null);
|
||||
|
||||
when(property.isIdProperty()).thenReturn(true);
|
||||
|
||||
entity.addPersistentProperty(property);
|
||||
|
||||
try {
|
||||
entity.addPersistentProperty(property);
|
||||
fail("Expected MappingException!");
|
||||
} catch (MappingException e) {
|
||||
// expected
|
||||
}
|
||||
}
|
||||
|
||||
private BasicPersistentEntity<Person, T> createEntity(Comparator<T> comparator) {
|
||||
return new BasicPersistentEntity<Person, T>(ClassTypeInformation.from(Person.class), comparator);
|
||||
}
|
||||
|
||||
@TypeAlias("foo")
|
||||
static class AliasedEntity {
|
||||
|
||||
}
|
||||
|
||||
static class Entity {
|
||||
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,137 @@
|
||||
/*
|
||||
* Copyright 2012 the original author or authors.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
package org.springframework.data.mapping.model;
|
||||
|
||||
import static org.hamcrest.CoreMatchers.*;
|
||||
import static org.junit.Assert.*;
|
||||
|
||||
import org.junit.Before;
|
||||
import org.junit.Test;
|
||||
import org.springframework.data.annotation.Id;
|
||||
import org.springframework.data.annotation.Version;
|
||||
import org.springframework.data.domain.Persistable;
|
||||
import org.springframework.data.mapping.MappingMetadataTests.SampleMappingContext;
|
||||
import org.springframework.data.mapping.model.MappingContextIsNewStrategyFactory.PropertyIsNullIsNewStrategy;
|
||||
import org.springframework.data.mapping.model.MappingContextIsNewStrategyFactory.PropertyIsNullOrZeroNumberIsNewStrategy;
|
||||
import org.springframework.data.support.IsNewStrategy;
|
||||
import org.springframework.data.support.IsNewStrategyFactory;
|
||||
|
||||
/**
|
||||
* @author Oliver Gierke
|
||||
*/
|
||||
public class MappingContextIsNewStrategyFactoryUnitTests {
|
||||
|
||||
IsNewStrategyFactory factory;
|
||||
|
||||
@Before
|
||||
public void setUp() {
|
||||
|
||||
SampleMappingContext context = new SampleMappingContext();
|
||||
factory = new MappingContextIsNewStrategyFactory(context);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void returnsPropertyIsNullOrZeroIsNewStrategyForVersionedEntity() {
|
||||
|
||||
IsNewStrategy strategy = factory.getIsNewStrategy(VersionedEntity.class);
|
||||
assertThat(strategy, is(instanceOf(PropertyIsNullOrZeroNumberIsNewStrategy.class)));
|
||||
|
||||
VersionedEntity entity = new VersionedEntity();
|
||||
assertThat(strategy.isNew(entity), is(true));
|
||||
|
||||
entity.id = 1L;
|
||||
assertThat(strategy.isNew(entity), is(true));
|
||||
|
||||
entity.version = 0L;
|
||||
assertThat(strategy.isNew(entity), is(true));
|
||||
|
||||
entity.version = 1L;
|
||||
assertThat(strategy.isNew(entity), is(false));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void returnsPropertyIsNullOrZeroIsNewStrategyForPrimitiveVersionedEntity() {
|
||||
|
||||
IsNewStrategy strategy = factory.getIsNewStrategy(VersionedEntity.class);
|
||||
assertThat(strategy, is(instanceOf(PropertyIsNullOrZeroNumberIsNewStrategy.class)));
|
||||
|
||||
VersionedEntity entity = new VersionedEntity();
|
||||
assertThat(strategy.isNew(entity), is(true));
|
||||
|
||||
entity.id = 1L;
|
||||
assertThat(strategy.isNew(entity), is(true));
|
||||
|
||||
entity.version = 1L;
|
||||
assertThat(strategy.isNew(entity), is(false));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void returnsPropertyIsNullIsNewStrategyForEntity() {
|
||||
|
||||
IsNewStrategy strategy = factory.getIsNewStrategy(Entity.class);
|
||||
assertThat(strategy, is(instanceOf(PropertyIsNullIsNewStrategy.class)));
|
||||
|
||||
Entity entity = new Entity();
|
||||
assertThat(strategy.isNew(entity), is(true));
|
||||
|
||||
entity.id = 1L;
|
||||
assertThat(strategy.isNew(entity), is(false));
|
||||
}
|
||||
|
||||
@SuppressWarnings("serial")
|
||||
static class PersistableEntity implements Persistable<Long> {
|
||||
|
||||
@Version
|
||||
Long version;
|
||||
|
||||
@Id
|
||||
Long id;
|
||||
|
||||
boolean isNew = true;
|
||||
|
||||
public Long getId() {
|
||||
return id;
|
||||
}
|
||||
|
||||
public boolean isNew() {
|
||||
return isNew;
|
||||
}
|
||||
}
|
||||
|
||||
static class VersionedEntity {
|
||||
|
||||
@Version
|
||||
Long version;
|
||||
|
||||
@Id
|
||||
Long id;
|
||||
}
|
||||
|
||||
static class PrimitveVersionedEntity {
|
||||
|
||||
@Version
|
||||
long version = 0;
|
||||
|
||||
@Id
|
||||
Long id;
|
||||
}
|
||||
|
||||
static class Entity {
|
||||
|
||||
@Id
|
||||
Long id;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,112 @@
|
||||
/*
|
||||
* Copyright 2012 the original author or authors.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
package org.springframework.data.mapping.model;
|
||||
|
||||
import static org.hamcrest.CoreMatchers.*;
|
||||
import static org.junit.Assert.*;
|
||||
|
||||
import java.util.Iterator;
|
||||
|
||||
import org.junit.Rule;
|
||||
import org.junit.Test;
|
||||
import org.junit.rules.ExpectedException;
|
||||
import org.junit.runner.RunWith;
|
||||
import org.mockito.Mock;
|
||||
import org.mockito.runners.MockitoJUnitRunner;
|
||||
import org.springframework.data.mapping.PersistentEntity;
|
||||
import org.springframework.data.mapping.PersistentProperty;
|
||||
import org.springframework.data.mapping.PreferredConstructor;
|
||||
import org.springframework.data.mapping.PreferredConstructor.Parameter;
|
||||
import org.springframework.data.mapping.model.PersistentEntityParameterValueProviderUnitTests.Outer.Inner;
|
||||
import org.springframework.data.util.ClassTypeInformation;
|
||||
|
||||
/**
|
||||
* Unit tests for {@link PersistentEntityParameterValueProvider}.
|
||||
*
|
||||
* @author Oliver Gierke
|
||||
*/
|
||||
@RunWith(MockitoJUnitRunner.class)
|
||||
public class PersistentEntityParameterValueProviderUnitTests<P extends PersistentProperty<P>> {
|
||||
|
||||
@Rule
|
||||
public ExpectedException exception = ExpectedException.none();
|
||||
|
||||
@Mock
|
||||
PropertyValueProvider<P> propertyValueProvider;
|
||||
@Mock
|
||||
P property;
|
||||
|
||||
/**
|
||||
* @see DATACMNS-134
|
||||
*/
|
||||
@Test
|
||||
public void usesParentObjectAsImplicitFirstConstructorArgument() {
|
||||
|
||||
Object outer = new Outer();
|
||||
|
||||
PersistentEntity<Inner, P> entity = new BasicPersistentEntity<Inner, P>(ClassTypeInformation.from(Inner.class)) {
|
||||
@Override
|
||||
public P getPersistentProperty(String name) {
|
||||
return property;
|
||||
}
|
||||
};
|
||||
PreferredConstructor<Inner, P> constructor = entity.getPersistenceConstructor();
|
||||
Iterator<Parameter<Object, P>> iterator = constructor.getParameters().iterator();
|
||||
|
||||
ParameterValueProvider<P> provider = new PersistentEntityParameterValueProvider<P>(entity, propertyValueProvider,
|
||||
outer);
|
||||
assertThat(provider.getParameterValue(iterator.next()), is(outer));
|
||||
assertThat(provider.getParameterValue(iterator.next()), is(nullValue()));
|
||||
assertThat(iterator.hasNext(), is(false));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void rejectsPropertyIfNameDoesNotMatch() {
|
||||
|
||||
PersistentEntity<Entity, P> entity = new BasicPersistentEntity<Entity, P>(ClassTypeInformation.from(Entity.class));
|
||||
ParameterValueProvider<P> provider = new PersistentEntityParameterValueProvider<P>(entity, propertyValueProvider,
|
||||
property);
|
||||
|
||||
PreferredConstructor<Entity, P> constructor = entity.getPersistenceConstructor();
|
||||
|
||||
exception.expect(MappingException.class);
|
||||
exception.expectMessage("bar");
|
||||
exception.expectMessage(Entity.class.getName());
|
||||
|
||||
provider.getParameterValue(constructor.getParameters().iterator().next());
|
||||
}
|
||||
|
||||
static class Outer {
|
||||
|
||||
class Inner {
|
||||
|
||||
Object myObject;
|
||||
|
||||
Inner(Object myObject) {
|
||||
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
static class Entity {
|
||||
|
||||
String foo;
|
||||
|
||||
public Entity(String bar) {
|
||||
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,120 @@
|
||||
/*
|
||||
* Copyright 2012 the original author or authors.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
package org.springframework.data.mapping.model;
|
||||
|
||||
import static org.hamcrest.CoreMatchers.*;
|
||||
import static org.junit.Assert.*;
|
||||
import static org.mockito.Mockito.*;
|
||||
|
||||
import org.junit.Before;
|
||||
import org.junit.Test;
|
||||
import org.junit.runner.RunWith;
|
||||
import org.mockito.Mock;
|
||||
import org.mockito.Mockito;
|
||||
import org.mockito.runners.MockitoJUnitRunner;
|
||||
import org.springframework.core.convert.ConversionService;
|
||||
import org.springframework.data.mapping.PreferredConstructor.Parameter;
|
||||
import org.springframework.data.mapping.model.AbstractPersistentPropertyUnitTests.SamplePersistentProperty;
|
||||
|
||||
/**
|
||||
* @author Oliver Gierke
|
||||
*/
|
||||
@RunWith(MockitoJUnitRunner.class)
|
||||
public class SpelExpressionParameterProviderUnitTests {
|
||||
|
||||
@Mock
|
||||
SpELExpressionEvaluator evaluator;
|
||||
@Mock
|
||||
ParameterValueProvider<SamplePersistentProperty> delegate;
|
||||
@Mock
|
||||
ConversionService conversionService;
|
||||
|
||||
SpELExpressionParameterValueProvider<SamplePersistentProperty> provider;
|
||||
|
||||
Parameter<Object, SamplePersistentProperty> parameter;
|
||||
|
||||
@Before
|
||||
@SuppressWarnings("unchecked")
|
||||
public void setUp() {
|
||||
provider = new SpELExpressionParameterValueProvider<SamplePersistentProperty>(evaluator, conversionService,
|
||||
delegate);
|
||||
|
||||
parameter = mock(Parameter.class);
|
||||
when(parameter.hasSpelExpression()).thenReturn(true);
|
||||
when(parameter.getRawType()).thenReturn(Object.class);
|
||||
}
|
||||
|
||||
@Test
|
||||
@SuppressWarnings("unchecked")
|
||||
public void delegatesIfParameterDoesNotHaveASpELExpression() {
|
||||
|
||||
Parameter<Object, SamplePersistentProperty> parameter = mock(Parameter.class);
|
||||
when(parameter.hasSpelExpression()).thenReturn(false);
|
||||
|
||||
provider.getParameterValue(parameter);
|
||||
verify(delegate, times(1)).getParameterValue(parameter);
|
||||
verify(evaluator, times(0)).evaluate("expression");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void evaluatesSpELExpression() {
|
||||
|
||||
when(parameter.getSpelExpression()).thenReturn("expression");
|
||||
|
||||
provider.getParameterValue(parameter);
|
||||
verify(delegate, times(0)).getParameterValue(parameter);
|
||||
verify(evaluator, times(1)).evaluate("expression");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void handsSpELValueToConversionService() {
|
||||
|
||||
when(evaluator.evaluate(Mockito.any(String.class))).thenReturn("value");
|
||||
|
||||
provider.getParameterValue(parameter);
|
||||
verify(delegate, times(0)).getParameterValue(parameter);
|
||||
verify(conversionService, times(1)).convert("value", Object.class);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void doesNotConvertNullValue() {
|
||||
|
||||
when(evaluator.evaluate(Mockito.any(String.class))).thenReturn(null);
|
||||
|
||||
provider.getParameterValue(parameter);
|
||||
verify(delegate, times(0)).getParameterValue(parameter);
|
||||
verify(conversionService, times(0)).convert("value", Object.class);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void returnsMassagedObjectOnOverride() {
|
||||
|
||||
provider = new SpELExpressionParameterValueProvider<SamplePersistentProperty>(evaluator, conversionService,
|
||||
delegate) {
|
||||
@Override
|
||||
@SuppressWarnings("unchecked")
|
||||
protected <T> T potentiallyConvertSpelValue(Object object, Parameter<T, SamplePersistentProperty> parameter) {
|
||||
return (T) "FOO";
|
||||
}
|
||||
};
|
||||
|
||||
when(evaluator.evaluate(Mockito.anyString())).thenReturn("value");
|
||||
|
||||
Object result = provider.getParameterValue(parameter);
|
||||
assertThat(result, is((Object) "FOO"));
|
||||
verify(delegate, times(0)).getParameterValue(parameter);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,62 @@
|
||||
/*
|
||||
* Copyright 2011 the original author or authors.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
package org.springframework.data.querydsl;
|
||||
|
||||
import static org.hamcrest.Matchers.*;
|
||||
import static org.junit.Assert.*;
|
||||
|
||||
import org.junit.Test;
|
||||
|
||||
import com.mysema.query.annotations.QueryEntity;
|
||||
|
||||
/**
|
||||
* Unit test for {@link SimpleEntityPathResolver}.
|
||||
*
|
||||
* @author Oliver Gierke
|
||||
*/
|
||||
public class SimpleEntityPathResolverUnitTests {
|
||||
|
||||
EntityPathResolver resolver = SimpleEntityPathResolver.INSTANCE;
|
||||
|
||||
@Test
|
||||
public void createsRepositoryFromDomainClassCorrectly() throws Exception {
|
||||
|
||||
assertThat((QUser) resolver.createPath(User.class), isA(QUser.class));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void resolvesEntityPathForInnerClassCorrectly() throws Exception {
|
||||
|
||||
assertThat((QSimpleEntityPathResolverUnitTests_NamedUser) resolver.createPath(NamedUser.class),
|
||||
isA(QSimpleEntityPathResolverUnitTests_NamedUser.class));
|
||||
}
|
||||
|
||||
@Test(expected = IllegalArgumentException.class)
|
||||
public void rejectsClassWithoutQueryClassConfrmingToTheNamingScheme() throws Exception {
|
||||
|
||||
resolver.createPath(QSimpleEntityPathResolverUnitTests_Sample.class);
|
||||
}
|
||||
|
||||
@QueryEntity
|
||||
static class Sample {
|
||||
|
||||
}
|
||||
|
||||
@QueryEntity
|
||||
static class NamedUser {
|
||||
|
||||
}
|
||||
}
|
||||
26
src/test/java/org/springframework/data/querydsl/User.java
Normal file
26
src/test/java/org/springframework/data/querydsl/User.java
Normal file
@@ -0,0 +1,26 @@
|
||||
/*
|
||||
* Copyright 2011 the original author or authors.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
package org.springframework.data.querydsl;
|
||||
|
||||
import com.mysema.query.annotations.QueryEntity;
|
||||
|
||||
/**
|
||||
* @author Oliver Gierke
|
||||
*/
|
||||
@QueryEntity
|
||||
public class User {
|
||||
|
||||
}
|
||||
@@ -0,0 +1,123 @@
|
||||
/*
|
||||
* Copyright 2011 the original author or authors.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
package org.springframework.data.repository.cdi;
|
||||
|
||||
import static org.hamcrest.Matchers.*;
|
||||
import static org.junit.Assert.*;
|
||||
|
||||
import java.io.Serializable;
|
||||
import java.lang.annotation.Annotation;
|
||||
import java.lang.reflect.Type;
|
||||
import java.util.Arrays;
|
||||
import java.util.Collections;
|
||||
import java.util.Set;
|
||||
|
||||
import javax.enterprise.context.spi.CreationalContext;
|
||||
import javax.enterprise.inject.spi.BeanManager;
|
||||
|
||||
import org.junit.Test;
|
||||
import org.junit.runner.RunWith;
|
||||
import org.mockito.Mock;
|
||||
import org.mockito.runners.MockitoJUnitRunner;
|
||||
import org.springframework.data.repository.Repository;
|
||||
|
||||
/**
|
||||
* Unit tests for {@link CdiRepositoryBean}.
|
||||
*
|
||||
* @author Oliver Gierke
|
||||
*/
|
||||
@RunWith(MockitoJUnitRunner.class)
|
||||
public class CdiRepositoryBeanUnitTests {
|
||||
|
||||
static final Set<Annotation> NO_ANNOTATIONS = Collections.emptySet();
|
||||
|
||||
@Mock
|
||||
BeanManager beanManager;
|
||||
|
||||
@Test(expected = IllegalArgumentException.class)
|
||||
public void voidRejectsNullQualifiers() {
|
||||
new DummyCdiRepositoryBean<SampleRepository>(null, SampleRepository.class, beanManager);
|
||||
}
|
||||
|
||||
@Test(expected = IllegalArgumentException.class)
|
||||
public void voidRejectsNullRepositoryType() {
|
||||
new DummyCdiRepositoryBean<SampleRepository>(NO_ANNOTATIONS, null, beanManager);
|
||||
}
|
||||
|
||||
@Test(expected = IllegalArgumentException.class)
|
||||
public void voidRejectsNullBeanManager() {
|
||||
new DummyCdiRepositoryBean<SampleRepository>(NO_ANNOTATIONS, SampleRepository.class, null);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void returnsBasicMetadata() {
|
||||
|
||||
DummyCdiRepositoryBean<SampleRepository> bean = new DummyCdiRepositoryBean<SampleRepository>(NO_ANNOTATIONS,
|
||||
SampleRepository.class, beanManager);
|
||||
|
||||
assertThat(bean.getBeanClass(), is(typeCompatibleWith(SampleRepository.class)));
|
||||
assertThat(bean.getName(), is(SampleRepository.class.getName()));
|
||||
assertThat(bean.isNullable(), is(false));
|
||||
}
|
||||
|
||||
@Test
|
||||
@SuppressWarnings("unchecked")
|
||||
public void returnsAllImplementedTypes() {
|
||||
|
||||
DummyCdiRepositoryBean<SampleRepository> bean = new DummyCdiRepositoryBean<SampleRepository>(NO_ANNOTATIONS,
|
||||
SampleRepository.class, beanManager);
|
||||
|
||||
Set<Type> types = bean.getTypes();
|
||||
assertThat(types.size(), is(2));
|
||||
assertThat(types.containsAll(Arrays.asList(SampleRepository.class, Repository.class)), is(true));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void detectsStereotypes() {
|
||||
|
||||
DummyCdiRepositoryBean<StereotypedSampleRepository> bean = new DummyCdiRepositoryBean<StereotypedSampleRepository>(
|
||||
NO_ANNOTATIONS, StereotypedSampleRepository.class, beanManager);
|
||||
|
||||
Set<Class<? extends Annotation>> stereotypes = bean.getStereotypes();
|
||||
assertThat(stereotypes.size(), is(1));
|
||||
assertThat(stereotypes, hasItem(StereotypeAnnotation.class));
|
||||
}
|
||||
|
||||
static class DummyCdiRepositoryBean<T> extends CdiRepositoryBean<T> {
|
||||
|
||||
public DummyCdiRepositoryBean(Set<Annotation> qualifiers, Class<T> repositoryType, BeanManager beanManager) {
|
||||
super(qualifiers, repositoryType, beanManager);
|
||||
}
|
||||
|
||||
public Class<? extends Annotation> getScope() {
|
||||
return null;
|
||||
}
|
||||
|
||||
@Override
|
||||
protected T create(CreationalContext<T> creationalContext, Class<T> repositoryType) {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
static interface SampleRepository extends Repository<Object, Serializable> {
|
||||
|
||||
}
|
||||
|
||||
@StereotypeAnnotation
|
||||
static interface StereotypedSampleRepository {
|
||||
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,40 @@
|
||||
/*
|
||||
* Copyright 2011 the original author or authors.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
package org.springframework.data.repository.cdi;
|
||||
|
||||
import static org.junit.Assert.*;
|
||||
import static org.hamcrest.CoreMatchers.*;
|
||||
|
||||
import org.junit.Test;
|
||||
|
||||
/**
|
||||
* Common integration tests for Spring Data repository CDI extension.
|
||||
*
|
||||
* @author Oliver Gierke
|
||||
*/
|
||||
public abstract class CdiRepositoryExtensionSupportIntegrationTests {
|
||||
|
||||
@Test
|
||||
public void createsSpringDataRepositoryBean() {
|
||||
|
||||
assertThat(getBean(SampleRepository.class), is(notNullValue()));
|
||||
|
||||
RepositoryClient client = getBean(RepositoryClient.class);
|
||||
assertThat(client.repository, is(notNullValue()));
|
||||
}
|
||||
|
||||
protected abstract <T> T getBean(Class<T> type);
|
||||
}
|
||||
@@ -0,0 +1,68 @@
|
||||
/*
|
||||
* Copyright 2011 the original author or authors.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
package org.springframework.data.repository.cdi;
|
||||
|
||||
import java.lang.annotation.Annotation;
|
||||
import java.lang.annotation.Retention;
|
||||
import java.lang.annotation.RetentionPolicy;
|
||||
import java.util.Map.Entry;
|
||||
import java.util.Set;
|
||||
|
||||
import javax.enterprise.context.NormalScope;
|
||||
import javax.enterprise.context.spi.CreationalContext;
|
||||
import javax.enterprise.event.Observes;
|
||||
import javax.enterprise.inject.spi.AfterBeanDiscovery;
|
||||
import javax.enterprise.inject.spi.BeanManager;
|
||||
|
||||
import org.mockito.Mockito;
|
||||
|
||||
/**
|
||||
* Dummy extension of {@link CdiRepositoryExtensionSupport} to allow integration tests. Will create mocks for repository
|
||||
* interfaces being found.
|
||||
*
|
||||
* @author Oliver Gierke
|
||||
*/
|
||||
public class DummyCdiExtension extends CdiRepositoryExtensionSupport {
|
||||
|
||||
@SuppressWarnings({ "rawtypes", "unchecked" })
|
||||
void afterBeanDiscovery(@Observes AfterBeanDiscovery afterBeanDiscovery, BeanManager beanManager) {
|
||||
for (Entry<Class<?>, Set<Annotation>> type : getRepositoryTypes()) {
|
||||
afterBeanDiscovery.addBean(new DummyCdiRepositoryBean(type.getValue(), type.getKey(), beanManager));
|
||||
}
|
||||
}
|
||||
|
||||
static class DummyCdiRepositoryBean<T> extends CdiRepositoryBean<T> {
|
||||
|
||||
public DummyCdiRepositoryBean(Set<Annotation> qualifiers, Class<T> repositoryType, BeanManager beanManager) {
|
||||
super(qualifiers, repositoryType, beanManager);
|
||||
}
|
||||
|
||||
public Class<? extends Annotation> getScope() {
|
||||
return MyScope.class;
|
||||
}
|
||||
|
||||
@Override
|
||||
protected T create(CreationalContext<T> creationalContext, Class<T> repositoryType) {
|
||||
return Mockito.mock(repositoryType);
|
||||
}
|
||||
}
|
||||
|
||||
@NormalScope
|
||||
@Retention(RetentionPolicy.RUNTIME)
|
||||
@interface MyScope {
|
||||
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,28 @@
|
||||
/*
|
||||
* Copyright 2011 the original author or authors.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
package org.springframework.data.repository.cdi;
|
||||
|
||||
import javax.inject.Inject;
|
||||
|
||||
/**
|
||||
*
|
||||
* @author Oliver Gierke
|
||||
*/
|
||||
class RepositoryClient {
|
||||
|
||||
@Inject
|
||||
SampleRepository repository;
|
||||
}
|
||||
@@ -0,0 +1,28 @@
|
||||
/*
|
||||
* Copyright 2011 the original author or authors.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
package org.springframework.data.repository.cdi;
|
||||
|
||||
import java.io.Serializable;
|
||||
|
||||
import org.springframework.data.repository.Repository;
|
||||
|
||||
/**
|
||||
*
|
||||
* @author Oliver Gierke
|
||||
*/
|
||||
public interface SampleRepository extends Repository<Object, Serializable> {
|
||||
|
||||
}
|
||||
@@ -0,0 +1,27 @@
|
||||
/*
|
||||
* Copyright 2011 the original author or authors.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
package org.springframework.data.repository.cdi;
|
||||
|
||||
import java.lang.annotation.Retention;
|
||||
import java.lang.annotation.RetentionPolicy;
|
||||
|
||||
import javax.enterprise.inject.Stereotype;
|
||||
|
||||
@Stereotype
|
||||
@Retention(RetentionPolicy.RUNTIME)
|
||||
@interface StereotypeAnnotation {
|
||||
|
||||
}
|
||||
@@ -0,0 +1,49 @@
|
||||
/*
|
||||
* Copyright 2011 the original author or authors.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
package org.springframework.data.repository.cdi;
|
||||
|
||||
import org.apache.webbeans.cditest.CdiTestContainer;
|
||||
import org.apache.webbeans.cditest.CdiTestContainerLoader;
|
||||
import org.junit.AfterClass;
|
||||
import org.junit.BeforeClass;
|
||||
|
||||
/**
|
||||
* CDI extension integration test using OpenWebbeans.
|
||||
*
|
||||
* @author Oliver Gierke
|
||||
*/
|
||||
public class WebbeansCdiRepositoryExtensionSupportIntegrationTests extends
|
||||
CdiRepositoryExtensionSupportIntegrationTests {
|
||||
|
||||
static CdiTestContainer container;
|
||||
|
||||
@BeforeClass
|
||||
public static void setUp() throws Exception {
|
||||
|
||||
container = CdiTestContainerLoader.getCdiContainer();
|
||||
container.bootContainer();
|
||||
}
|
||||
|
||||
@Override
|
||||
protected <T> T getBean(Class<T> type) {
|
||||
return container.getInstance(type);
|
||||
}
|
||||
|
||||
@AfterClass
|
||||
public static void tearDown() throws Exception {
|
||||
container.shutdownContainer();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,95 @@
|
||||
/*
|
||||
* Copyright 2012 the original author or authors.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
package org.springframework.data.repository.config;
|
||||
|
||||
import static org.hamcrest.Matchers.*;
|
||||
import static org.junit.Assert.*;
|
||||
|
||||
import java.util.Collection;
|
||||
|
||||
import org.junit.Before;
|
||||
import org.junit.Test;
|
||||
import org.springframework.core.io.DefaultResourceLoader;
|
||||
import org.springframework.core.type.AnnotationMetadata;
|
||||
import org.springframework.core.type.StandardAnnotationMetadata;
|
||||
|
||||
/**
|
||||
* Unit tests for {@link AnnotationRepositoryConfigurationSource}.
|
||||
*
|
||||
* @author Oliver Gierke
|
||||
*/
|
||||
public class AnnotationRepositoryConfigurationSourceUnitTests {
|
||||
|
||||
RepositoryConfigurationSource source;
|
||||
|
||||
@Before
|
||||
public void setUp() {
|
||||
|
||||
AnnotationMetadata annotationMetadata = new StandardAnnotationMetadata(SampleConfiguration.class, true);
|
||||
source = new AnnotationRepositoryConfigurationSource(annotationMetadata, EnableRepositories.class);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void findsBasePackagesForClasses() {
|
||||
|
||||
Iterable<String> basePackages = source.getBasePackages();
|
||||
assertThat(basePackages, hasItem(AnnotationRepositoryConfigurationSourceUnitTests.class.getPackage().getName()));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void evaluatesExcludeFiltersCorrectly() {
|
||||
|
||||
Collection<String> candidates = source.getCandidates(new DefaultResourceLoader());
|
||||
assertThat(candidates, hasSize(1));
|
||||
assertThat(candidates, hasItem(MyRepository.class.getName()));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void defaultsToPackageOfAnnotatedClass() {
|
||||
|
||||
AnnotationMetadata metadata = new StandardAnnotationMetadata(DefaultConfiguration.class);
|
||||
RepositoryConfigurationSource source = new AnnotationRepositoryConfigurationSource(metadata,
|
||||
EnableRepositories.class);
|
||||
|
||||
Iterable<String> packages = source.getBasePackages();
|
||||
assertThat(packages, hasItem(DefaultConfiguration.class.getPackage().getName()));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void returnsConfiguredBasePackage() {
|
||||
|
||||
AnnotationMetadata metadata = new StandardAnnotationMetadata(DefaultConfigurationWithBasePackage.class);
|
||||
RepositoryConfigurationSource source = new AnnotationRepositoryConfigurationSource(metadata,
|
||||
EnableRepositories.class);
|
||||
|
||||
Iterable<String> packages = source.getBasePackages();
|
||||
assertThat(packages, hasItem("foo"));
|
||||
}
|
||||
|
||||
public static class Person {
|
||||
|
||||
}
|
||||
|
||||
@EnableRepositories
|
||||
static class DefaultConfiguration {
|
||||
|
||||
}
|
||||
|
||||
@EnableRepositories(basePackages = "foo")
|
||||
static class DefaultConfigurationWithBasePackage {
|
||||
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,50 @@
|
||||
/*
|
||||
* Copyright 2012 the original author or authors.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
package org.springframework.data.repository.config;
|
||||
|
||||
import static org.hamcrest.CoreMatchers.*;
|
||||
import static org.junit.Assert.*;
|
||||
|
||||
import org.junit.Test;
|
||||
import org.junit.runner.RunWith;
|
||||
import org.mockito.Mock;
|
||||
import org.mockito.runners.MockitoJUnitRunner;
|
||||
import org.springframework.data.repository.query.QueryLookupStrategy.Key;
|
||||
|
||||
/**
|
||||
* Unit tests for {@link DefaultRepositoryConfiguration}.
|
||||
*
|
||||
* @author Oliver Gierke
|
||||
*/
|
||||
@RunWith(MockitoJUnitRunner.class)
|
||||
public class DefaultRepositoryConfigurationUnitTests {
|
||||
|
||||
@Mock
|
||||
RepositoryConfigurationSource source;
|
||||
|
||||
@Test
|
||||
public void supportsBasicConfiguration() {
|
||||
|
||||
RepositoryConfiguration<RepositoryConfigurationSource> configuration = new DefaultRepositoryConfiguration<RepositoryConfigurationSource>(
|
||||
source, "com.acme.MyRepository");
|
||||
|
||||
assertThat(configuration.getConfigurationSource(), is(source));
|
||||
assertThat(configuration.getImplementationBeanName(), is("myRepositoryImpl"));
|
||||
assertThat(configuration.getImplementationClassName(), is("MyRepositoryImpl"));
|
||||
assertThat(configuration.getRepositoryInterface(), is("com.acme.MyRepository"));
|
||||
assertThat(configuration.getQueryLookupStrategyKey(), is((Object) Key.CREATE_IF_NOT_FOUND));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,47 @@
|
||||
/*
|
||||
* Copyright 2012 the original author or authors.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
package org.springframework.data.repository.config;
|
||||
|
||||
import java.lang.annotation.Inherited;
|
||||
import java.lang.annotation.Retention;
|
||||
import java.lang.annotation.RetentionPolicy;
|
||||
|
||||
import org.springframework.context.annotation.ComponentScan.Filter;
|
||||
import org.springframework.context.annotation.Import;
|
||||
import org.springframework.data.repository.config.RepositoryBeanDefinitionRegistrarSupportUnitTests.DummyRegistrar;
|
||||
import org.springframework.data.repository.core.support.DummyRepositoryFactoryBean;
|
||||
|
||||
@Retention(RetentionPolicy.RUNTIME)
|
||||
@Import(DummyRegistrar.class)
|
||||
@Inherited
|
||||
public @interface EnableRepositories {
|
||||
|
||||
String[] value() default {};
|
||||
|
||||
String[] basePackages() default {};
|
||||
|
||||
Class<?>[] basePackageClasses() default {};
|
||||
|
||||
Filter[] includeFilters() default {};
|
||||
|
||||
Filter[] excludeFilters() default {};
|
||||
|
||||
Class<?> repositoryFactoryBeanClass() default DummyRepositoryFactoryBean.class;
|
||||
|
||||
String namedQueriesLocation() default "";
|
||||
|
||||
String repositoryImplementationPostfix() default "Impl";
|
||||
}
|
||||
@@ -0,0 +1,23 @@
|
||||
/*
|
||||
* Copyright 2012 the original author or authors.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
package org.springframework.data.repository.config;
|
||||
|
||||
import org.springframework.data.repository.Repository;
|
||||
import org.springframework.data.repository.config.AnnotationRepositoryConfigurationSourceUnitTests.Person;
|
||||
|
||||
interface MyOtherRepository extends Repository<Person, Long> {
|
||||
|
||||
}
|
||||
@@ -0,0 +1,23 @@
|
||||
/*
|
||||
* Copyright 2012 the original author or authors.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
package org.springframework.data.repository.config;
|
||||
|
||||
import org.springframework.data.repository.Repository;
|
||||
import org.springframework.data.repository.config.AnnotationRepositoryConfigurationSourceUnitTests.Person;
|
||||
|
||||
interface MyRepository extends Repository<Person, Long> {
|
||||
|
||||
}
|
||||
@@ -0,0 +1,49 @@
|
||||
/*
|
||||
* Copyright 2012 the original author or authors.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
package org.springframework.data.repository.config;
|
||||
|
||||
import static org.hamcrest.CoreMatchers.*;
|
||||
import static org.junit.Assert.*;
|
||||
|
||||
import org.junit.Test;
|
||||
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
|
||||
/**
|
||||
* @author Oliver Gierke
|
||||
*/
|
||||
public class RepositoryBeanDefinitionRegistrarSupportIntegrationTests {
|
||||
|
||||
@Configuration
|
||||
@EnableRepositories
|
||||
static class SampleConfig {
|
||||
|
||||
}
|
||||
|
||||
@Configuration
|
||||
static class TestConfig extends SampleConfig {
|
||||
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testBootstrappingWithInheritedConfigClasses() {
|
||||
|
||||
AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(TestConfig.class);
|
||||
|
||||
assertThat(context.getBean(MyRepository.class), is(notNullValue()));
|
||||
assertThat(context.getBean(MyOtherRepository.class), is(notNullValue()));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,84 @@
|
||||
/*
|
||||
* Copyright 2012 the original author or authors.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
package org.springframework.data.repository.config;
|
||||
|
||||
import static org.mockito.Matchers.*;
|
||||
import static org.mockito.Mockito.*;
|
||||
|
||||
import java.lang.annotation.Annotation;
|
||||
|
||||
import org.junit.Test;
|
||||
import org.junit.runner.RunWith;
|
||||
import org.mockito.Mock;
|
||||
import org.mockito.runners.MockitoJUnitRunner;
|
||||
import org.springframework.beans.factory.config.BeanDefinition;
|
||||
import org.springframework.beans.factory.support.BeanDefinitionRegistry;
|
||||
import org.springframework.core.type.AnnotationMetadata;
|
||||
import org.springframework.core.type.StandardAnnotationMetadata;
|
||||
import org.springframework.data.repository.core.support.RepositoryFactoryBeanSupport;
|
||||
|
||||
/**
|
||||
* Integration test for {@link RepositoryBeanDefinitionRegistrarSupport}.
|
||||
*
|
||||
* @author Oliver Gierke
|
||||
*/
|
||||
@RunWith(MockitoJUnitRunner.class)
|
||||
public class RepositoryBeanDefinitionRegistrarSupportUnitTests {
|
||||
|
||||
@Mock
|
||||
BeanDefinitionRegistry registry;
|
||||
|
||||
@Test
|
||||
public void registersBeanDefinitionForFoundBean() {
|
||||
|
||||
AnnotationMetadata metadata = new StandardAnnotationMetadata(SampleConfiguration.class, true);
|
||||
DummyRegistrar registrar = new DummyRegistrar();
|
||||
registrar.registerBeanDefinitions(metadata, registry);
|
||||
|
||||
verify(registry, times(1)).registerBeanDefinition(eq("myRepository"), any(BeanDefinition.class));
|
||||
}
|
||||
|
||||
static class DummyRegistrar extends RepositoryBeanDefinitionRegistrarSupport {
|
||||
|
||||
/*
|
||||
* (non-Javadoc)
|
||||
* @see org.springframework.data.repository.config.RepositoryBeanDefinitionRegistrarSupport#getAnnotation()
|
||||
*/
|
||||
@Override
|
||||
protected Class<? extends Annotation> getAnnotation() {
|
||||
return EnableRepositories.class;
|
||||
}
|
||||
|
||||
/*
|
||||
* (non-Javadoc)
|
||||
* @see org.springframework.data.repository.config.RepositoryBeanDefinitionRegistrarSupport#getExtension()
|
||||
*/
|
||||
@Override
|
||||
protected RepositoryConfigurationExtension getExtension() {
|
||||
return new RepositoryConfigurationExtensionSupport() {
|
||||
|
||||
public String getRepositoryFactoryClassName() {
|
||||
return RepositoryFactoryBeanSupport.class.getName();
|
||||
}
|
||||
|
||||
@Override
|
||||
protected String getModulePrefix() {
|
||||
return "commons";
|
||||
}
|
||||
};
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,77 @@
|
||||
/*
|
||||
* Copyright 2012 the original author or authors.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
package org.springframework.data.repository.config;
|
||||
|
||||
import static org.hamcrest.CoreMatchers.*;
|
||||
import static org.junit.Assert.*;
|
||||
|
||||
import javax.inject.Named;
|
||||
|
||||
import org.junit.Before;
|
||||
import org.junit.Test;
|
||||
import org.springframework.beans.factory.config.BeanDefinition;
|
||||
import org.springframework.beans.factory.support.BeanDefinitionBuilder;
|
||||
import org.springframework.beans.factory.support.BeanDefinitionRegistry;
|
||||
import org.springframework.beans.factory.support.BeanNameGenerator;
|
||||
import org.springframework.beans.factory.support.DefaultListableBeanFactory;
|
||||
import org.springframework.data.repository.core.support.RepositoryFactoryBeanSupport;
|
||||
|
||||
/**
|
||||
* Unit tests for {@link RepositoryBeanNameGenerator}.
|
||||
*
|
||||
* @author Oliver Gierke
|
||||
*/
|
||||
public class RepositoryBeanNameGeneratorUnitTest {
|
||||
|
||||
BeanNameGenerator generator;
|
||||
BeanDefinitionRegistry registry;
|
||||
|
||||
@Before
|
||||
public void setUp() {
|
||||
|
||||
RepositoryBeanNameGenerator generator = new RepositoryBeanNameGenerator();
|
||||
generator.setBeanClassLoader(Thread.currentThread().getContextClassLoader());
|
||||
|
||||
this.generator = generator;
|
||||
this.registry = new DefaultListableBeanFactory();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void usesPlainClassNameIfNoAnnotationPresent() {
|
||||
assertThat(generator.generateBeanName(getBeanDefinitionFor(MyRepository.class), registry), is("myRepository"));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void usesAnnotationValueIfAnnotationPresent() {
|
||||
assertThat(generator.generateBeanName(getBeanDefinitionFor(AnnotatedInterface.class), registry), is("specialName"));
|
||||
}
|
||||
|
||||
private BeanDefinition getBeanDefinitionFor(Class<?> repositoryInterface) {
|
||||
|
||||
BeanDefinitionBuilder builder = BeanDefinitionBuilder.genericBeanDefinition(RepositoryFactoryBeanSupport.class);
|
||||
builder.addPropertyValue("repositoryInterface", repositoryInterface.getName());
|
||||
return builder.getBeanDefinition();
|
||||
}
|
||||
|
||||
interface PlainInterface {
|
||||
|
||||
}
|
||||
|
||||
@Named("specialName")
|
||||
interface AnnotatedInterface {
|
||||
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,60 @@
|
||||
/*
|
||||
* Copyright 2012 the original author or authors.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
package org.springframework.data.repository.config;
|
||||
|
||||
import static org.hamcrest.Matchers.*;
|
||||
import static org.junit.Assert.*;
|
||||
|
||||
import java.util.Arrays;
|
||||
import java.util.Collections;
|
||||
import java.util.List;
|
||||
import java.util.Set;
|
||||
|
||||
import org.junit.Test;
|
||||
import org.springframework.beans.factory.config.BeanDefinition;
|
||||
import org.springframework.core.type.filter.AssignableTypeFilter;
|
||||
import org.springframework.core.type.filter.TypeFilter;
|
||||
import org.springframework.data.repository.sample.SampleAnnotatedRepository;
|
||||
|
||||
/**
|
||||
* Unit tests for {@link RepositoryComponentProvider}.
|
||||
*
|
||||
* @author Oliver Gierke
|
||||
*/
|
||||
public class RepositoryComponentProviderUnitTests {
|
||||
|
||||
@Test
|
||||
public void findsAnnotatedRepositoryInterface() {
|
||||
|
||||
RepositoryComponentProvider provider = new RepositoryComponentProvider(Collections.<TypeFilter> emptyList());
|
||||
Set<BeanDefinition> components = provider.findCandidateComponents("org.springframework.data.repository.sample");
|
||||
|
||||
assertThat(components.size(), is(1));
|
||||
assertThat(components.iterator().next().getBeanClassName(), is(SampleAnnotatedRepository.class.getName()));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void limitsFoundRepositoriesToIncludeFiltersOnly() {
|
||||
|
||||
List<? extends TypeFilter> filters = Arrays.asList(new AssignableTypeFilter(MyOtherRepository.class));
|
||||
|
||||
RepositoryComponentProvider provider = new RepositoryComponentProvider(filters);
|
||||
Set<BeanDefinition> components = provider.findCandidateComponents("org.springframework.data.repository");
|
||||
|
||||
assertThat(components.size(), is(1));
|
||||
assertThat(components.iterator().next().getBeanClassName(), is(MyOtherRepository.class.getName()));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,97 @@
|
||||
/*
|
||||
* Copyright 2012 the original author or authors.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
package org.springframework.data.repository.config;
|
||||
|
||||
import static org.hamcrest.Matchers.*;
|
||||
import static org.junit.Assert.*;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
import org.junit.Test;
|
||||
import org.springframework.beans.factory.config.BeanDefinition;
|
||||
import org.springframework.beans.factory.support.DefaultListableBeanFactory;
|
||||
import org.springframework.beans.factory.xml.XmlBeanDefinitionReader;
|
||||
import org.springframework.core.io.ClassPathResource;
|
||||
import org.springframework.data.repository.init.JacksonResourceReader;
|
||||
import org.springframework.data.repository.init.ResourceReaderRepositoryPopulator;
|
||||
import org.springframework.data.repository.init.UnmarshallingResourceReader;
|
||||
import org.springframework.oxm.jaxb.Jaxb2Marshaller;
|
||||
import org.springframework.test.util.ReflectionTestUtils;
|
||||
|
||||
/**
|
||||
* Integratin tests for the initializer namespace elements.
|
||||
*
|
||||
* @author Oliver Gierke
|
||||
*/
|
||||
public class ResourceReaderRepositoryPopulatorBeanDefinitionParserIntegrationTests {
|
||||
|
||||
/**
|
||||
* @see DATACMNS-58
|
||||
*/
|
||||
@Test
|
||||
public void registersJacksonInitializerCorrectly() {
|
||||
|
||||
DefaultListableBeanFactory beanFactory = new DefaultListableBeanFactory();
|
||||
XmlBeanDefinitionReader reader = new XmlBeanDefinitionReader(beanFactory);
|
||||
reader.loadBeanDefinitions(new ClassPathResource("populators.xml", getClass()));
|
||||
|
||||
BeanDefinition definition = beanFactory.getBeanDefinition("jackson-populator");
|
||||
assertThat(definition, is(notNullValue()));
|
||||
|
||||
Object bean = beanFactory.getBean("jackson-populator");
|
||||
assertThat(bean, is(instanceOf(ResourceReaderRepositoryPopulator.class)));
|
||||
Object resourceReader = ReflectionTestUtils.getField(bean, "reader");
|
||||
assertThat(resourceReader, is(instanceOf(JacksonResourceReader.class)));
|
||||
|
||||
Object resources = ReflectionTestUtils.getField(bean, "resources");
|
||||
assertIsListOfClasspathResourcesWithPath(resources, "org/springframework/data/repository/init/data.json");
|
||||
}
|
||||
|
||||
/**
|
||||
* @see DATACMNS-58
|
||||
*/
|
||||
@Test
|
||||
public void registersXmlInitializerCorrectly() {
|
||||
|
||||
DefaultListableBeanFactory beanFactory = new DefaultListableBeanFactory();
|
||||
XmlBeanDefinitionReader reader = new XmlBeanDefinitionReader(beanFactory);
|
||||
reader.loadBeanDefinitions(new ClassPathResource("populators.xml", getClass()));
|
||||
|
||||
BeanDefinition definition = beanFactory.getBeanDefinition("xml-populator");
|
||||
assertThat(definition, is(notNullValue()));
|
||||
|
||||
Object bean = beanFactory.getBean("xml-populator");
|
||||
assertThat(bean, is(instanceOf(ResourceReaderRepositoryPopulator.class)));
|
||||
Object resourceReader = ReflectionTestUtils.getField(bean, "reader");
|
||||
assertThat(resourceReader, is(instanceOf(UnmarshallingResourceReader.class)));
|
||||
Object unmarshaller = ReflectionTestUtils.getField(resourceReader, "unmarshaller");
|
||||
assertThat(unmarshaller, is(instanceOf(Jaxb2Marshaller.class)));
|
||||
|
||||
Object resources = ReflectionTestUtils.getField(bean, "resources");
|
||||
assertIsListOfClasspathResourcesWithPath(resources, "org/springframework/data/repository/init/data.xml");
|
||||
}
|
||||
|
||||
private void assertIsListOfClasspathResourcesWithPath(Object source, String path) {
|
||||
|
||||
assertThat(source, is(instanceOf(List.class)));
|
||||
List<?> list = (List<?>) source;
|
||||
assertThat(list, is(not(empty())));
|
||||
Object element = list.get(0);
|
||||
assertThat(element, is(instanceOf(ClassPathResource.class)));
|
||||
ClassPathResource resource = (ClassPathResource) element;
|
||||
assertThat(resource.getPath(), is(path));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,24 @@
|
||||
/*
|
||||
* Copyright 2012 the original author or authors.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
package org.springframework.data.repository.config;
|
||||
|
||||
import org.springframework.context.annotation.ComponentScan.Filter;
|
||||
import org.springframework.context.annotation.FilterType;
|
||||
|
||||
@EnableRepositories(excludeFilters = @Filter(type = FilterType.ASSIGNABLE_TYPE, value = MyOtherRepository.class), basePackageClasses = AnnotationRepositoryConfigurationSourceUnitTests.class)
|
||||
class SampleConfiguration {
|
||||
|
||||
}
|
||||
@@ -0,0 +1,46 @@
|
||||
/*
|
||||
* Copyright 2011-2012 the original author or authors.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
package org.springframework.data.repository.core.support;
|
||||
|
||||
import static org.hamcrest.CoreMatchers.*;
|
||||
import static org.junit.Assert.*;
|
||||
|
||||
import java.io.Serializable;
|
||||
|
||||
import org.junit.Test;
|
||||
import org.springframework.data.repository.core.EntityInformation;
|
||||
|
||||
/**
|
||||
* Unit tests for {@link AbstractEntityInformation}.
|
||||
*
|
||||
* @author Oliver Gierke
|
||||
*/
|
||||
public class AbstractEntityInformationUnitTests {
|
||||
|
||||
@Test(expected = IllegalArgumentException.class)
|
||||
public void rejectsNullDomainClass() throws Exception {
|
||||
|
||||
new DummyEntityInformation<Object>(null);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void considersEntityNewIfGetIdReturnsNull() throws Exception {
|
||||
|
||||
EntityInformation<Object, Serializable> metadata = new DummyEntityInformation<Object>(Object.class);
|
||||
assertThat(metadata.isNew(null), is(true));
|
||||
assertThat(metadata.isNew(new Object()), is(false));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,127 @@
|
||||
/*
|
||||
* Copyright 2011-2012 the original author or authors.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
package org.springframework.data.repository.core.support;
|
||||
|
||||
import static org.hamcrest.Matchers.*;
|
||||
import static org.junit.Assert.*;
|
||||
|
||||
import java.io.Serializable;
|
||||
import java.lang.reflect.Method;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
import org.junit.Test;
|
||||
import org.springframework.data.domain.Page;
|
||||
import org.springframework.data.domain.Pageable;
|
||||
import org.springframework.data.querydsl.User;
|
||||
import org.springframework.data.repository.Repository;
|
||||
import org.springframework.data.repository.core.RepositoryMetadata;
|
||||
|
||||
/**
|
||||
* Unit tests for {@link AbstractRepositoryMetadata}.
|
||||
*
|
||||
* @author Oliver Gierke
|
||||
*/
|
||||
public class AbstractRepositoryMetadataUnitTests {
|
||||
|
||||
@Test
|
||||
public void discoversSimpleReturnTypeCorrectly() throws Exception {
|
||||
|
||||
RepositoryMetadata metadata = new DummyRepositoryMetadata(UserRepository.class);
|
||||
Method method = UserRepository.class.getMethod("findSingle");
|
||||
assertThat(metadata.getReturnedDomainClass(method), is(typeCompatibleWith(User.class)));
|
||||
}
|
||||
|
||||
/**
|
||||
* @see DATACMNS-98
|
||||
*/
|
||||
@Test
|
||||
public void resolvesTypeParameterReturnType() throws Exception {
|
||||
RepositoryMetadata metadata = new DummyRepositoryMetadata(ConcreteRepository.class);
|
||||
Method method = ConcreteRepository.class.getMethod("intermediateMethod");
|
||||
assertThat(metadata.getReturnedDomainClass(method), is(typeCompatibleWith(User.class)));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void determinesReturnTypeFromPageable() throws Exception {
|
||||
|
||||
RepositoryMetadata metadata = new DummyRepositoryMetadata(ExtendingRepository.class);
|
||||
Method method = ExtendingRepository.class.getMethod("findByFirstname", Pageable.class, String.class);
|
||||
assertThat(metadata.getReturnedDomainClass(method), is(typeCompatibleWith(User.class)));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void determinesReturnTypeFromGenericType() throws Exception {
|
||||
RepositoryMetadata metadata = new DummyRepositoryMetadata(ExtendingRepository.class);
|
||||
Method method = ExtendingRepository.class.getMethod("someMethod");
|
||||
assertThat(metadata.getReturnedDomainClass(method), is(typeCompatibleWith(GenericType.class)));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void handlesGenericTypeInReturnedCollectionCorrectly() throws SecurityException, NoSuchMethodException {
|
||||
|
||||
RepositoryMetadata metadata = new DummyRepositoryMetadata(ExtendingRepository.class);
|
||||
Method method = ExtendingRepository.class.getMethod("anotherMethod");
|
||||
assertThat(metadata.getReturnedDomainClass(method), is(typeCompatibleWith(Map.class)));
|
||||
}
|
||||
|
||||
interface UserRepository extends Repository<User, Long> {
|
||||
|
||||
User findSingle();
|
||||
}
|
||||
|
||||
interface IntermediateRepository<T> extends Repository<T, Long> {
|
||||
|
||||
List<T> intermediateMethod();
|
||||
}
|
||||
|
||||
interface ConcreteRepository extends IntermediateRepository<User> {
|
||||
|
||||
}
|
||||
|
||||
interface ExtendingRepository extends Serializable, UserRepository {
|
||||
|
||||
Page<User> findByFirstname(Pageable pageable, String firstname);
|
||||
|
||||
GenericType<User> someMethod();
|
||||
|
||||
List<Map<String, Object>> anotherMethod();
|
||||
}
|
||||
|
||||
class GenericType<T> {
|
||||
|
||||
}
|
||||
|
||||
class DummyRepositoryMetadata extends AbstractRepositoryMetadata {
|
||||
|
||||
public DummyRepositoryMetadata(Class<?> repositoryInterface) {
|
||||
super(repositoryInterface);
|
||||
}
|
||||
|
||||
public Class<? extends Serializable> getIdType() {
|
||||
return null;
|
||||
}
|
||||
|
||||
public Class<?> getDomainType() {
|
||||
return null;
|
||||
}
|
||||
|
||||
public Class<?> getRepositoryInterface() {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,66 @@
|
||||
/*
|
||||
* Copyright 2011 the original author or authors.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
package org.springframework.data.repository.core.support;
|
||||
|
||||
import static org.junit.Assert.*;
|
||||
|
||||
import org.junit.Test;
|
||||
import org.springframework.data.repository.RepositoryDefinition;
|
||||
import org.springframework.data.repository.core.RepositoryMetadata;
|
||||
import org.springframework.data.repository.core.support.AnnotationRepositoryMetadata;
|
||||
import org.springframework.data.repository.core.support.DefaultRepositoryMetadata;
|
||||
|
||||
/**
|
||||
* Unit tests for {@link DefaultRepositoryMetadata}.
|
||||
*
|
||||
* @author Oliver Gierke
|
||||
*/
|
||||
public class AnnotationRepositoryMetadataUnitTests {
|
||||
|
||||
@Test
|
||||
public void handlesRepositoryProxyAnnotationCorrectly() {
|
||||
|
||||
RepositoryMetadata metadata = new AnnotationRepositoryMetadata(AnnotatedRepository.class);
|
||||
assertEquals(User.class, metadata.getDomainType());
|
||||
assertEquals(Integer.class, metadata.getIdType());
|
||||
}
|
||||
|
||||
@Test(expected = IllegalArgumentException.class)
|
||||
public void preventsUnannotatedInterface() {
|
||||
|
||||
new AnnotationRepositoryMetadata(UnannotatedRepository.class);
|
||||
}
|
||||
|
||||
@SuppressWarnings("unused")
|
||||
private class User {
|
||||
|
||||
private String firstname;
|
||||
|
||||
public String getAddress() {
|
||||
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
@RepositoryDefinition(domainClass = User.class, idClass = Integer.class)
|
||||
interface AnnotatedRepository {
|
||||
|
||||
}
|
||||
|
||||
interface UnannotatedRepository {
|
||||
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,87 @@
|
||||
/*
|
||||
* Copyright 2011 the original author or authors.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
package org.springframework.data.repository.core.support;
|
||||
|
||||
import static org.hamcrest.CoreMatchers.*;
|
||||
import static org.junit.Assert.*;
|
||||
|
||||
import org.junit.Test;
|
||||
import org.springframework.data.repository.core.support.TransactionalRepositoryProxyPostProcessor;
|
||||
import org.springframework.data.repository.core.support.TransactionalRepositoryProxyPostProcessor.CustomAnnotationTransactionAttributeSource;
|
||||
import org.springframework.transaction.annotation.Transactional;
|
||||
import org.springframework.transaction.interceptor.TransactionAttribute;
|
||||
|
||||
/**
|
||||
* Unit tests for {@link CustomAnnotationTransactionAttributeSource}.
|
||||
*
|
||||
* @author Oliver Gierke
|
||||
*/
|
||||
public class CustomAnnotationTransactionAttributeSourceUnitTests {
|
||||
|
||||
@Test
|
||||
public void usesCustomTransactionConfigurationOnInterface() throws SecurityException, NoSuchMethodException {
|
||||
|
||||
CustomAnnotationTransactionAttributeSource source = new TransactionalRepositoryProxyPostProcessor.CustomAnnotationTransactionAttributeSource();
|
||||
|
||||
TransactionAttribute attribute = source.getTransactionAttribute(Bar.class.getMethod("bar", Object.class),
|
||||
FooImpl.class);
|
||||
assertThat(attribute.isReadOnly(), is(false));
|
||||
|
||||
attribute = source.getTransactionAttribute(Bar.class.getMethod("foo"), FooImpl.class);
|
||||
assertThat(attribute.isReadOnly(), is(false));
|
||||
}
|
||||
|
||||
/**
|
||||
* Basic interface.
|
||||
*
|
||||
* @author Oliver Gierke
|
||||
*/
|
||||
interface Foo<T> {
|
||||
|
||||
void foo();
|
||||
|
||||
void bar(T param);
|
||||
}
|
||||
|
||||
/**
|
||||
* Implementation defining transaction configuration.
|
||||
*
|
||||
* @author Oliver Gierke
|
||||
*/
|
||||
@Transactional(readOnly = true)
|
||||
class FooImpl implements Foo<Object> {
|
||||
|
||||
@Transactional
|
||||
public void foo() {
|
||||
|
||||
}
|
||||
|
||||
public void bar(Object param) {
|
||||
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Interface reconfiguring transactions.
|
||||
*
|
||||
* @author Oliver Gierke
|
||||
*/
|
||||
interface Bar extends Foo<Object> {
|
||||
|
||||
@Transactional
|
||||
void bar(Object param);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,231 @@
|
||||
package org.springframework.data.repository.core.support;
|
||||
|
||||
import static org.hamcrest.Matchers.*;
|
||||
import static org.junit.Assert.*;
|
||||
|
||||
import java.io.Serializable;
|
||||
import java.lang.reflect.Method;
|
||||
import java.util.List;
|
||||
|
||||
import org.hamcrest.Matcher;
|
||||
import org.hamcrest.collection.IsEmptyIterable;
|
||||
import org.junit.Test;
|
||||
import org.junit.runner.RunWith;
|
||||
import org.mockito.Mock;
|
||||
import org.mockito.runners.MockitoJUnitRunner;
|
||||
import org.springframework.data.domain.Page;
|
||||
import org.springframework.data.domain.Pageable;
|
||||
import org.springframework.data.domain.Sort;
|
||||
import org.springframework.data.repository.CrudRepository;
|
||||
import org.springframework.data.repository.PagingAndSortingRepository;
|
||||
import org.springframework.data.repository.Repository;
|
||||
import org.springframework.data.repository.core.RepositoryInformation;
|
||||
import org.springframework.data.repository.core.RepositoryMetadata;
|
||||
import org.springframework.data.repository.core.support.DefaultRepositoryMetadataUnitTests.DummyGenericRepositorySupport;
|
||||
|
||||
/**
|
||||
* @author Oliver Gierke
|
||||
*/
|
||||
@RunWith(MockitoJUnitRunner.class)
|
||||
public class DefaultRepositoryInformationUnitTests {
|
||||
|
||||
@SuppressWarnings("rawtypes")
|
||||
static final Class<DummyGenericRepositorySupport> REPOSITORY = DummyGenericRepositorySupport.class;
|
||||
|
||||
@Mock
|
||||
FooRepositoryCustom customImplementation;
|
||||
|
||||
@Test
|
||||
public void discoversRepositoryBaseClassMethod() throws Exception {
|
||||
|
||||
Method method = FooRepository.class.getMethod("findOne", Integer.class);
|
||||
RepositoryMetadata metadata = new DefaultRepositoryMetadata(FooRepository.class);
|
||||
DefaultRepositoryInformation information = new DefaultRepositoryInformation(metadata, REPOSITORY, null);
|
||||
|
||||
Method reference = information.getTargetClassMethod(method);
|
||||
assertEquals(REPOSITORY, reference.getDeclaringClass());
|
||||
assertThat(reference.getName(), is("findOne"));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void discoveresNonRepositoryBaseClassMethod() throws Exception {
|
||||
|
||||
Method method = FooRepository.class.getMethod("findOne", Long.class);
|
||||
|
||||
RepositoryMetadata metadata = new DefaultRepositoryMetadata(FooRepository.class);
|
||||
DefaultRepositoryInformation information = new DefaultRepositoryInformation(metadata, CrudRepository.class, null);
|
||||
|
||||
assertThat(information.getTargetClassMethod(method), is(method));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void discoversCustomlyImplementedCrudMethod() throws SecurityException, NoSuchMethodException {
|
||||
|
||||
RepositoryMetadata metadata = new DefaultRepositoryMetadata(FooRepository.class);
|
||||
RepositoryInformation information = new DefaultRepositoryInformation(metadata, CrudRepository.class,
|
||||
customImplementation.getClass());
|
||||
|
||||
Method source = FooRepositoryCustom.class.getMethod("save", User.class);
|
||||
Method expected = customImplementation.getClass().getMethod("save", User.class);
|
||||
|
||||
assertThat(information.getTargetClassMethod(source), is(expected));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void considersIntermediateMethodsAsFinderMethods() {
|
||||
|
||||
RepositoryMetadata metadata = new DefaultRepositoryMetadata(ConcreteRepository.class);
|
||||
RepositoryInformation information = new DefaultRepositoryInformation(metadata, CrudRepository.class, null);
|
||||
|
||||
assertThat(information.hasCustomMethod(), is(false));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void discoversIntermediateMethodsAsBackingMethods() throws NoSuchMethodException, SecurityException {
|
||||
|
||||
DefaultRepositoryMetadata metadata = new DefaultRepositoryMetadata(CustomRepository.class);
|
||||
DefaultRepositoryInformation information = new DefaultRepositoryInformation(metadata,
|
||||
PagingAndSortingRepository.class, null);
|
||||
|
||||
Method method = CustomRepository.class.getMethod("findAll", Pageable.class);
|
||||
assertThat(information.isBaseClassMethod(method), is(true));
|
||||
|
||||
method = getMethodFrom(CustomRepository.class, "exists");
|
||||
assertThat(information.isBaseClassMethod(method), is(true));
|
||||
|
||||
Matcher<Iterable<Method>> empty = iterableWithSize(0);
|
||||
assertThat(information.getQueryMethods(), is(empty));
|
||||
}
|
||||
|
||||
/**
|
||||
* @see DATACMNS-151
|
||||
*/
|
||||
@Test
|
||||
public void doesNotConsiderManuallyDefinedSaveMethodAQueryMethod() {
|
||||
|
||||
RepositoryMetadata metadata = new DefaultRepositoryMetadata(CustomRepository.class);
|
||||
RepositoryInformation information = new DefaultRepositoryInformation(metadata, PagingAndSortingRepository.class,
|
||||
null);
|
||||
assertThat(information.getQueryMethods(), is(IsEmptyIterable.<Method> emptyIterable()));
|
||||
}
|
||||
|
||||
/**
|
||||
* @see DATACMNS-151
|
||||
*/
|
||||
@Test
|
||||
public void doesNotConsiderRedeclaredSaveMethodAQueryMethod() throws Exception {
|
||||
|
||||
RepositoryMetadata metadata = new DefaultRepositoryMetadata(ConcreteRepository.class);
|
||||
RepositoryInformation information = new DefaultRepositoryInformation(metadata, CrudRepository.class, null);
|
||||
|
||||
Method saveMethod = BaseRepository.class.getMethod("save", Object.class);
|
||||
Method deleteMethod = BaseRepository.class.getMethod("delete", Object.class);
|
||||
|
||||
Iterable<Method> queryMethods = information.getQueryMethods();
|
||||
|
||||
assertThat(queryMethods, not(hasItem(saveMethod)));
|
||||
assertThat(queryMethods, not(hasItem(deleteMethod)));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void onlyReturnsMostConcreteQueryMethod() throws Exception {
|
||||
|
||||
RepositoryMetadata metadata = new DefaultRepositoryMetadata(ConcreteRepository.class);
|
||||
RepositoryInformation information = new DefaultRepositoryInformation(metadata, CrudRepository.class, null);
|
||||
|
||||
Method intermediateMethod = BaseRepository.class.getMethod("genericMethodToOverride", String.class);
|
||||
Method concreteMethod = ConcreteRepository.class.getMethod("genericMethodToOverride", String.class);
|
||||
|
||||
Iterable<Method> queryMethods = information.getQueryMethods();
|
||||
|
||||
assertThat(queryMethods, hasItem(concreteMethod));
|
||||
assertThat(queryMethods, not(hasItem(intermediateMethod)));
|
||||
}
|
||||
|
||||
/**
|
||||
* @see DATACMNS-193
|
||||
*/
|
||||
@Test
|
||||
public void detectsQueryMethodCorrectly() {
|
||||
|
||||
RepositoryMetadata metadata = new DefaultRepositoryMetadata(ConcreteRepository.class);
|
||||
RepositoryInformation information = new DefaultRepositoryInformation(metadata, CrudRepository.class, null);
|
||||
|
||||
Method queryMethod = getMethodFrom(ConcreteRepository.class, "findBySomethingDifferent");
|
||||
|
||||
assertThat(information.getQueryMethods(), hasItem(queryMethod));
|
||||
assertThat(information.isQueryMethod(queryMethod), is(true));
|
||||
}
|
||||
|
||||
private Method getMethodFrom(Class<?> type, String name) {
|
||||
for (Method method : type.getMethods()) {
|
||||
if (method.getName().equals(name)) {
|
||||
return method;
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
interface FooRepository extends CrudRepository<User, Integer>, FooRepositoryCustom {
|
||||
|
||||
// Redeclared method
|
||||
User findOne(Integer primaryKey);
|
||||
|
||||
// Not a redeclared method
|
||||
User findOne(Long primaryKey);
|
||||
}
|
||||
|
||||
interface FooRepositoryCustom {
|
||||
|
||||
User save(User user);
|
||||
}
|
||||
|
||||
@SuppressWarnings("unused")
|
||||
private class User {
|
||||
|
||||
private String firstname;
|
||||
|
||||
public String getAddress() {
|
||||
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
interface BaseRepository<S, ID extends Serializable> extends CrudRepository<S, ID> {
|
||||
|
||||
S findBySomething(String something);
|
||||
|
||||
S genericMethodToOverride(String something);
|
||||
|
||||
<K extends S> K save(K entity);
|
||||
|
||||
void delete(S entity);
|
||||
}
|
||||
|
||||
interface ConcreteRepository extends BaseRepository<User, Integer> {
|
||||
|
||||
User findBySomethingDifferent(String somethingDifferent);
|
||||
|
||||
User genericMethodToOverride(String something);
|
||||
}
|
||||
|
||||
interface ReadOnlyRepository<T, ID extends Serializable> extends Repository<T, ID> {
|
||||
|
||||
T findOne(ID id);
|
||||
|
||||
Iterable<T> findAll();
|
||||
|
||||
Page<T> findAll(Pageable pageable);
|
||||
|
||||
List<T> findAll(Sort sort);
|
||||
|
||||
boolean exists(ID id);
|
||||
|
||||
long count();
|
||||
}
|
||||
|
||||
interface CustomRepository extends ReadOnlyRepository<Object, Long> {
|
||||
|
||||
Object save(Object object);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,146 @@
|
||||
/*
|
||||
* Copyright 2011-2012 the original author or authors.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
package org.springframework.data.repository.core.support;
|
||||
|
||||
import static org.junit.Assert.*;
|
||||
|
||||
import java.io.Serializable;
|
||||
import java.util.Collection;
|
||||
|
||||
import org.junit.Test;
|
||||
import org.springframework.data.domain.Page;
|
||||
import org.springframework.data.domain.Pageable;
|
||||
import org.springframework.data.repository.CrudRepository;
|
||||
import org.springframework.data.repository.core.RepositoryMetadata;
|
||||
import org.springframework.data.repository.util.ClassUtils;
|
||||
|
||||
/**
|
||||
* Unit tests for {@link DefaultRepositoryMetadata}.
|
||||
*
|
||||
* @author Oliver Gierke
|
||||
*/
|
||||
public class DefaultRepositoryMetadataUnitTests {
|
||||
|
||||
@Test(expected = IllegalArgumentException.class)
|
||||
public void preventsNullRepositoryInterface() {
|
||||
|
||||
new DefaultRepositoryMetadata(null);
|
||||
}
|
||||
|
||||
@Test(expected = IllegalArgumentException.class)
|
||||
public void rejectsNonInterface() {
|
||||
new DefaultRepositoryMetadata(Object.class);
|
||||
}
|
||||
|
||||
@Test(expected = IllegalArgumentException.class)
|
||||
public void rejectsNonRepositoryInterface() {
|
||||
new DefaultRepositoryMetadata(Collection.class);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void looksUpDomainClassCorrectly() throws Exception {
|
||||
|
||||
RepositoryMetadata metadata = new DefaultRepositoryMetadata(UserRepository.class);
|
||||
assertEquals(User.class, metadata.getDomainType());
|
||||
|
||||
metadata = new DefaultRepositoryMetadata(SomeDao.class);
|
||||
assertEquals(User.class, metadata.getDomainType());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void findsDomainClassOnExtensionOfDaoInterface() throws Exception {
|
||||
|
||||
RepositoryMetadata metadata = new DefaultRepositoryMetadata(ExtensionOfUserCustomExtendedDao.class);
|
||||
assertEquals(User.class, metadata.getDomainType());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void detectsParameterizedEntitiesCorrectly() {
|
||||
|
||||
RepositoryMetadata metadata = new DefaultRepositoryMetadata(GenericEntityRepository.class);
|
||||
assertEquals(GenericEntity.class, metadata.getDomainType());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void looksUpIdClassCorrectly() throws Exception {
|
||||
|
||||
RepositoryMetadata metadata = new DefaultRepositoryMetadata(UserRepository.class);
|
||||
|
||||
assertEquals(Integer.class, metadata.getIdType());
|
||||
}
|
||||
|
||||
@SuppressWarnings("unused")
|
||||
private class User {
|
||||
|
||||
private String firstname;
|
||||
|
||||
public String getAddress() {
|
||||
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
static interface UserRepository extends CrudRepository<User, Integer> {
|
||||
|
||||
}
|
||||
|
||||
/**
|
||||
* Sample interface to serve two purposes:
|
||||
* <ol>
|
||||
* <li>Check that {@link ClassUtils#getDomainClass(Class)} skips non {@link GenericDao} interfaces</li>
|
||||
* <li>Check that {@link ClassUtils#getDomainClass(Class)} traverses interface hierarchy</li>
|
||||
* </ol>
|
||||
*
|
||||
* @author Oliver Gierke
|
||||
*/
|
||||
private interface SomeDao extends Serializable, UserRepository {
|
||||
|
||||
Page<User> findByFirstname(Pageable pageable, String firstname);
|
||||
}
|
||||
|
||||
/**
|
||||
* Sample interface to test recursive lookup of domain class.
|
||||
*
|
||||
* @author Oliver Gierke
|
||||
*/
|
||||
static interface ExtensionOfUserCustomExtendedDao extends UserCustomExtendedRepository {
|
||||
|
||||
}
|
||||
|
||||
static interface UserCustomExtendedRepository extends CrudRepository<User, Integer> {
|
||||
|
||||
}
|
||||
|
||||
static abstract class DummyGenericRepositorySupport<T, ID extends Serializable> implements CrudRepository<T, ID> {
|
||||
|
||||
public T findOne(ID id) {
|
||||
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Helper class to reproduce #256.
|
||||
*
|
||||
* @author Oliver Gierke
|
||||
*/
|
||||
static class GenericEntity<T> {
|
||||
}
|
||||
|
||||
static interface GenericEntityRepository extends CrudRepository<GenericEntity<String>, Long> {
|
||||
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,51 @@
|
||||
/*
|
||||
* Copyright 2012 the original author or authors.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
package org.springframework.data.repository.core.support;
|
||||
|
||||
import java.io.Serializable;
|
||||
|
||||
/**
|
||||
* Dummy implementation of {@link AbstractEntityInformation}.
|
||||
*
|
||||
* @author Oliver Gierke
|
||||
*/
|
||||
public class DummyEntityInformation<T> extends AbstractEntityInformation<T, Serializable> {
|
||||
|
||||
/**
|
||||
* Creates a new {@link DummyEntityInformation} for the given domain class.
|
||||
*
|
||||
* @param domainClass
|
||||
*/
|
||||
public DummyEntityInformation(Class<T> domainClass) {
|
||||
super(domainClass);
|
||||
}
|
||||
|
||||
/*
|
||||
* (non-Javadoc)
|
||||
* @see org.springframework.data.repository.core.EntityInformation#getId(java.lang.Object)
|
||||
*/
|
||||
public Serializable getId(Object entity) {
|
||||
return entity == null ? null : entity.toString();
|
||||
}
|
||||
|
||||
/*
|
||||
* (non-Javadoc)
|
||||
* @see org.springframework.data.repository.core.EntityInformation#getIdType()
|
||||
*/
|
||||
public Class<Serializable> getIdType() {
|
||||
return Serializable.class;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,86 @@
|
||||
/*
|
||||
* Copyright 2012 the original author or authors.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
package org.springframework.data.repository.core.support;
|
||||
|
||||
import static org.mockito.Mockito.*;
|
||||
|
||||
import java.io.Serializable;
|
||||
import java.lang.reflect.Method;
|
||||
|
||||
import org.mockito.Mockito;
|
||||
import org.springframework.data.repository.core.EntityInformation;
|
||||
import org.springframework.data.repository.core.NamedQueries;
|
||||
import org.springframework.data.repository.core.RepositoryMetadata;
|
||||
import org.springframework.data.repository.core.support.RepositoryFactorySupportUnitTests.MyRepositoryQuery;
|
||||
import org.springframework.data.repository.query.QueryLookupStrategy;
|
||||
import org.springframework.data.repository.query.QueryLookupStrategy.Key;
|
||||
import org.springframework.data.repository.query.RepositoryQuery;
|
||||
|
||||
public class DummyRepositoryFactory extends RepositoryFactorySupport {
|
||||
|
||||
private final Object repository;
|
||||
|
||||
public DummyRepositoryFactory(Object repository) {
|
||||
this.repository = repository;
|
||||
}
|
||||
|
||||
/*
|
||||
* (non-Javadoc)
|
||||
* @see org.springframework.data.repository.core.support.RepositoryFactorySupport#getEntityInformation(java.lang.Class)
|
||||
*/
|
||||
@Override
|
||||
@SuppressWarnings("unchecked")
|
||||
public <T, ID extends Serializable> EntityInformation<T, ID> getEntityInformation(Class<T> domainClass) {
|
||||
|
||||
return mock(EntityInformation.class);
|
||||
}
|
||||
|
||||
/*
|
||||
* (non-Javadoc)
|
||||
* @see org.springframework.data.repository.core.support.RepositoryFactorySupport#getTargetRepository(org.springframework.data.repository.core.RepositoryMetadata)
|
||||
*/
|
||||
@Override
|
||||
protected Object getTargetRepository(RepositoryMetadata metadata) {
|
||||
return repository;
|
||||
}
|
||||
|
||||
/*
|
||||
* (non-Javadoc)
|
||||
* @see org.springframework.data.repository.core.support.RepositoryFactorySupport#getRepositoryBaseClass(org.springframework.data.repository.core.RepositoryMetadata)
|
||||
*/
|
||||
@Override
|
||||
protected Class<?> getRepositoryBaseClass(RepositoryMetadata metadata) {
|
||||
return repository.getClass();
|
||||
}
|
||||
|
||||
/*
|
||||
* (non-Javadoc)
|
||||
* @see org.springframework.data.repository.core.support.RepositoryFactorySupport#getQueryLookupStrategy(org.springframework.data.repository.query.QueryLookupStrategy.Key)
|
||||
*/
|
||||
@Override
|
||||
protected QueryLookupStrategy getQueryLookupStrategy(Key key) {
|
||||
|
||||
MyRepositoryQuery queryOne = mock(MyRepositoryQuery.class);
|
||||
RepositoryQuery queryTwo = mock(RepositoryQuery.class);
|
||||
|
||||
QueryLookupStrategy strategy = mock(QueryLookupStrategy.class);
|
||||
when(
|
||||
strategy.resolveQuery(Mockito.any(Method.class), Mockito.any(RepositoryMetadata.class),
|
||||
Mockito.any(NamedQueries.class))).thenReturn(queryOne, queryTwo);
|
||||
|
||||
return strategy;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,40 @@
|
||||
/*
|
||||
* Copyright 2012 the original author or authors.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
package org.springframework.data.repository.core.support;
|
||||
|
||||
import static org.mockito.Mockito.*;
|
||||
|
||||
import java.io.Serializable;
|
||||
|
||||
import org.springframework.data.repository.Repository;
|
||||
|
||||
/**
|
||||
* @author Oliver Gierke
|
||||
*/
|
||||
public class DummyRepositoryFactoryBean<T extends Repository<S, ID>, S, ID extends Serializable> extends
|
||||
RepositoryFactoryBeanSupport<T, S, ID> {
|
||||
|
||||
/*
|
||||
* (non-Javadoc)
|
||||
* @see org.springframework.data.repository.core.support.RepositoryFactoryBeanSupport#createRepositoryFactory()
|
||||
*/
|
||||
@Override
|
||||
protected RepositoryFactorySupport createRepositoryFactory() {
|
||||
|
||||
Repository<?, ?> repository = mock(Repository.class);
|
||||
return new DummyRepositoryFactory(repository);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,84 @@
|
||||
/*
|
||||
* Copyright 2011 the original author or authors.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
package org.springframework.data.repository.core.support;
|
||||
|
||||
import static org.hamcrest.CoreMatchers.*;
|
||||
import static org.junit.Assert.*;
|
||||
import static org.mockito.Mockito.*;
|
||||
|
||||
import org.junit.Test;
|
||||
import org.junit.runner.RunWith;
|
||||
import org.mockito.Mock;
|
||||
import org.mockito.runners.MockitoJUnitRunner;
|
||||
import org.springframework.data.domain.Persistable;
|
||||
import org.springframework.data.repository.core.support.PersistableEntityInformation;
|
||||
|
||||
/**
|
||||
* Unit tests for {@link PersistableEntityMetadata}.
|
||||
*
|
||||
* @author Oliver Gierke
|
||||
*/
|
||||
@RunWith(MockitoJUnitRunner.class)
|
||||
public class PersistableEntityInformationUnitTests {
|
||||
|
||||
@SuppressWarnings({ "rawtypes", "unchecked" })
|
||||
static final PersistableEntityInformation metadata = new PersistableEntityInformation(Persistable.class);
|
||||
|
||||
@Mock
|
||||
Persistable<Long> persistable;
|
||||
|
||||
@Test
|
||||
@SuppressWarnings("unchecked")
|
||||
public void usesPersistablesGetId() throws Exception {
|
||||
|
||||
when(persistable.getId()).thenReturn(2L, 1L, 3L);
|
||||
assertEquals(2L, metadata.getId(persistable));
|
||||
assertEquals(1L, metadata.getId(persistable));
|
||||
assertEquals(3L, metadata.getId(persistable));
|
||||
}
|
||||
|
||||
@Test
|
||||
@SuppressWarnings("unchecked")
|
||||
public void usesPersistablesIsNew() throws Exception {
|
||||
|
||||
when(persistable.isNew()).thenReturn(true, false);
|
||||
assertThat(metadata.isNew(persistable), is(true));
|
||||
assertThat(metadata.isNew(persistable), is(false));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void returnsGivenClassAsEntityType() throws Exception {
|
||||
|
||||
PersistableEntityInformation<PersistableEntity, Long> info = new PersistableEntityInformation<PersistableEntity, Long>(
|
||||
PersistableEntity.class);
|
||||
|
||||
assertEquals(PersistableEntity.class, info.getJavaType());
|
||||
}
|
||||
|
||||
@SuppressWarnings("serial")
|
||||
static class PersistableEntity implements Persistable<Long> {
|
||||
|
||||
public Long getId() {
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
public boolean isNew() {
|
||||
|
||||
return false;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,68 @@
|
||||
/*
|
||||
* Copyright 2011 the original author or authors.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
package org.springframework.data.repository.core.support;
|
||||
|
||||
import static org.mockito.Matchers.*;
|
||||
import static org.mockito.Mockito.*;
|
||||
|
||||
import java.lang.reflect.Method;
|
||||
import java.util.Arrays;
|
||||
import java.util.Collections;
|
||||
|
||||
import org.junit.Test;
|
||||
import org.junit.runner.RunWith;
|
||||
import org.mockito.Mock;
|
||||
import org.mockito.runners.MockitoJUnitRunner;
|
||||
import org.springframework.data.repository.core.NamedQueries;
|
||||
import org.springframework.data.repository.core.RepositoryInformation;
|
||||
import org.springframework.data.repository.core.RepositoryMetadata;
|
||||
import org.springframework.data.repository.query.QueryLookupStrategy;
|
||||
import org.springframework.data.repository.query.QueryLookupStrategy.Key;
|
||||
|
||||
/**
|
||||
* Unit test for {@link QueryExecuterMethodInterceptor}.
|
||||
*
|
||||
* @author Oliver Gierke
|
||||
*/
|
||||
@RunWith(MockitoJUnitRunner.class)
|
||||
public class QueryExecutorMethodInterceptorUnitTests {
|
||||
|
||||
@Mock
|
||||
RepositoryFactorySupport factory;
|
||||
@Mock
|
||||
RepositoryInformation information;
|
||||
@Mock
|
||||
QueryLookupStrategy strategy;
|
||||
|
||||
@Test(expected = IllegalStateException.class)
|
||||
public void rejectsRepositoryInterfaceWithQueryMethodsIfNoQueryLookupStrategyIsDefined() throws Exception {
|
||||
|
||||
when(information.getQueryMethods()).thenReturn(Arrays.asList(Object.class.getMethod("toString")));
|
||||
when(factory.getQueryLookupStrategy(any(Key.class))).thenReturn(null);
|
||||
|
||||
factory.new QueryExecutorMethodInterceptor(information, null, new Object());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void skipsQueryLookupsIfQueryLookupStrategyIsNull() {
|
||||
|
||||
when(information.getQueryMethods()).thenReturn(Collections.<Method> emptySet());
|
||||
when(factory.getQueryLookupStrategy(any(Key.class))).thenReturn(strategy);
|
||||
|
||||
factory.new QueryExecutorMethodInterceptor(information, null, new Object());
|
||||
verify(strategy, times(0)).resolveQuery(any(Method.class), any(RepositoryMetadata.class), any(NamedQueries.class));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,65 @@
|
||||
/*
|
||||
* Copyright 2012 the original author or authors.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may
|
||||
import java.io.Serializable;
|
||||
not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
package org.springframework.data.repository.core.support;
|
||||
|
||||
import static org.hamcrest.Matchers.*;
|
||||
import static org.junit.Assert.*;
|
||||
|
||||
import java.io.Serializable;
|
||||
|
||||
import org.junit.Test;
|
||||
import org.springframework.data.annotation.Id;
|
||||
import org.springframework.data.repository.core.EntityInformation;
|
||||
|
||||
/**
|
||||
* Unit tests for {@link ReflectionEntityInformation}.
|
||||
*
|
||||
* @author Oliver Gierke
|
||||
*/
|
||||
public class ReflectionEntityInformationUnitTests {
|
||||
|
||||
@Test
|
||||
public void discoversAnnotationOnField() {
|
||||
|
||||
EntityInformation<Sample, Serializable> information = getEntityInformation(Sample.class);
|
||||
assertThat(information.getIdType(), is(typeCompatibleWith(String.class)));
|
||||
}
|
||||
|
||||
/**
|
||||
* @see DATACMNS-170
|
||||
*/
|
||||
@Test(expected = IllegalArgumentException.class)
|
||||
public void rejectsTypeWithoutAnnotatedField() {
|
||||
getEntityInformation(Unannotated.class);
|
||||
}
|
||||
|
||||
private static <T> EntityInformation<T, Serializable> getEntityInformation(Class<T> type) {
|
||||
return new ReflectionEntityInformation<T, Serializable>(type, Id.class);
|
||||
}
|
||||
|
||||
static class Sample {
|
||||
|
||||
@Id
|
||||
String id;
|
||||
}
|
||||
|
||||
static class Unannotated {
|
||||
|
||||
String id;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,165 @@
|
||||
/*
|
||||
* Copyright 2011 the original author or authors.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
package org.springframework.data.repository.core.support;
|
||||
|
||||
import static org.hamcrest.CoreMatchers.*;
|
||||
import static org.junit.Assert.*;
|
||||
import static org.mockito.Mockito.*;
|
||||
|
||||
import java.io.Serializable;
|
||||
import java.util.List;
|
||||
|
||||
import org.junit.Before;
|
||||
import org.junit.Test;
|
||||
import org.junit.runner.RunWith;
|
||||
import org.mockito.Mock;
|
||||
import org.mockito.Mockito;
|
||||
import org.mockito.runners.MockitoJUnitRunner;
|
||||
import org.springframework.data.domain.Page;
|
||||
import org.springframework.data.domain.PageRequest;
|
||||
import org.springframework.data.domain.Pageable;
|
||||
import org.springframework.data.domain.Sort;
|
||||
import org.springframework.data.repository.PagingAndSortingRepository;
|
||||
import org.springframework.data.repository.Repository;
|
||||
import org.springframework.data.repository.RepositoryDefinition;
|
||||
import org.springframework.data.repository.query.RepositoryQuery;
|
||||
|
||||
/**
|
||||
* Unit tests for {@link RepositoryFactorySupport}.
|
||||
*
|
||||
* @author Oliver Gierke
|
||||
*/
|
||||
@RunWith(MockitoJUnitRunner.class)
|
||||
public class RepositoryFactorySupportUnitTests {
|
||||
|
||||
RepositoryFactorySupport factory;
|
||||
|
||||
@Mock
|
||||
PagingAndSortingRepository<Object, Serializable> backingRepo;
|
||||
@Mock
|
||||
ObjectRepositoryCustom customImplementation;
|
||||
|
||||
@Mock
|
||||
MyQueryCreationListener listener;
|
||||
@Mock
|
||||
PlainQueryCreationListener otherListener;
|
||||
|
||||
@Before
|
||||
public void setUp() {
|
||||
factory = new DummyRepositoryFactory(backingRepo);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void invokesCustomQueryCreationListenerForSpecialRepositoryQueryOnly() throws Exception {
|
||||
|
||||
factory.addQueryCreationListener(listener);
|
||||
factory.addQueryCreationListener(otherListener);
|
||||
|
||||
factory.getRepository(ObjectRepository.class);
|
||||
|
||||
verify(listener, times(1)).onCreation(Mockito.any(MyRepositoryQuery.class));
|
||||
verify(otherListener, times(2)).onCreation(Mockito.any(RepositoryQuery.class));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void routesCallToRedeclaredMethodIntoTarget() {
|
||||
|
||||
ObjectRepository repository = factory.getRepository(ObjectRepository.class);
|
||||
repository.save(repository);
|
||||
|
||||
verify(backingRepo, times(1)).save(Mockito.any(Object.class));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void invokesCustomMethodIfItRedeclaresACRUDOne() {
|
||||
|
||||
ObjectRepository repository = factory.getRepository(ObjectRepository.class, customImplementation);
|
||||
repository.findOne(1);
|
||||
|
||||
verify(customImplementation, times(1)).findOne(1);
|
||||
verify(backingRepo, times(0)).findOne(1);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void createsRepositoryInstanceWithCustomIntermediateRepository() {
|
||||
|
||||
CustomRepository repository = factory.getRepository(CustomRepository.class);
|
||||
Pageable pageable = new PageRequest(0, 10);
|
||||
repository.findAll(pageable);
|
||||
|
||||
verify(backingRepo, times(1)).findAll(pageable);
|
||||
}
|
||||
|
||||
@Test
|
||||
@SuppressWarnings("unchecked")
|
||||
public void createsProxyForAnnotatedRepository() {
|
||||
|
||||
Class<?> repositoryInterface = AnnotatedRepository.class;
|
||||
Class<? extends Repository<?, ?>> foo = (Class<? extends Repository<?, ?>>) repositoryInterface;
|
||||
|
||||
assertThat(factory.getRepository(foo), is(notNullValue()));
|
||||
}
|
||||
|
||||
interface ObjectRepository extends Repository<Object, Serializable>, ObjectRepositoryCustom {
|
||||
|
||||
Object findByClass(Class<?> clazz);
|
||||
|
||||
Object findByFoo();
|
||||
|
||||
Object save(Object entity);
|
||||
}
|
||||
|
||||
interface ObjectRepositoryCustom {
|
||||
|
||||
Object findOne(Serializable id);
|
||||
}
|
||||
|
||||
interface PlainQueryCreationListener extends QueryCreationListener<RepositoryQuery> {
|
||||
|
||||
}
|
||||
|
||||
interface MyQueryCreationListener extends QueryCreationListener<MyRepositoryQuery> {
|
||||
|
||||
}
|
||||
|
||||
interface MyRepositoryQuery extends RepositoryQuery {
|
||||
|
||||
}
|
||||
|
||||
interface ReadOnlyRepository<T, ID extends Serializable> extends Repository<T, ID> {
|
||||
|
||||
T findOne(ID id);
|
||||
|
||||
Iterable<T> findAll();
|
||||
|
||||
Page<T> findAll(Pageable pageable);
|
||||
|
||||
List<T> findAll(Sort sort);
|
||||
|
||||
boolean exists(ID id);
|
||||
|
||||
long count();
|
||||
}
|
||||
|
||||
interface CustomRepository extends ReadOnlyRepository<Object, Long> {
|
||||
|
||||
}
|
||||
|
||||
@RepositoryDefinition(domainClass = Object.class, idClass = Long.class)
|
||||
interface AnnotatedRepository {
|
||||
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,112 @@
|
||||
/*
|
||||
* Copyright 2008-2010 the original author or authors.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
|
||||
* use this file except in compliance with the License. You may obtain a copy of
|
||||
* the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
|
||||
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
|
||||
* License for the specific language governing permissions and limitations under
|
||||
* the License.
|
||||
*/
|
||||
package org.springframework.data.repository.core.support;
|
||||
|
||||
import static org.hamcrest.CoreMatchers.*;
|
||||
import static org.junit.Assert.*;
|
||||
import static org.mockito.Mockito.*;
|
||||
|
||||
import org.junit.Before;
|
||||
import org.junit.Test;
|
||||
import org.junit.runner.RunWith;
|
||||
import org.mockito.Mock;
|
||||
import org.mockito.runners.MockitoJUnitRunner;
|
||||
import org.springframework.beans.factory.BeanFactory;
|
||||
import org.springframework.beans.factory.config.BeanDefinition;
|
||||
import org.springframework.beans.factory.config.ConfigurableListableBeanFactory;
|
||||
import org.springframework.beans.factory.support.BeanDefinitionBuilder;
|
||||
import org.springframework.data.repository.Repository;
|
||||
import org.springframework.data.repository.core.support.RepositoryFactoryBeanSupport;
|
||||
import org.springframework.data.repository.core.support.RepositoryInterfaceAwareBeanPostProcessor;
|
||||
|
||||
/**
|
||||
* Unit tests for {@link RepositoryInterfaceAwareBeanPostProcessor}.
|
||||
*
|
||||
* @author Oliver Gierke
|
||||
*/
|
||||
@RunWith(MockitoJUnitRunner.class)
|
||||
public class RepositoryInterfaceAwareBeanPostProcessorUnitTests {
|
||||
|
||||
private static final Class<?> FACTORY_CLASS = RepositoryFactoryBeanSupport.class;
|
||||
private static final String BEAN_NAME = "foo";
|
||||
private static final String DAO_INTERFACE_PROPERTY = "repositoryInterface";
|
||||
|
||||
private RepositoryInterfaceAwareBeanPostProcessor processor;
|
||||
|
||||
@Mock
|
||||
private ConfigurableListableBeanFactory beanFactory;
|
||||
private BeanDefinition beanDefinition;
|
||||
|
||||
@Before
|
||||
public void setUp() {
|
||||
|
||||
BeanDefinitionBuilder builder = BeanDefinitionBuilder.rootBeanDefinition(FACTORY_CLASS).addPropertyValue(
|
||||
DAO_INTERFACE_PROPERTY, UserDao.class);
|
||||
this.beanDefinition = builder.getBeanDefinition();
|
||||
|
||||
when(beanFactory.getBeanDefinition(BEAN_NAME)).thenReturn(beanDefinition);
|
||||
|
||||
processor = new RepositoryInterfaceAwareBeanPostProcessor();
|
||||
|
||||
}
|
||||
|
||||
@Test
|
||||
public void returnsDaoInterfaceClassForFactoryBean() throws Exception {
|
||||
|
||||
processor.setBeanFactory(beanFactory);
|
||||
assertEquals(UserDao.class, processor.predictBeanType(FACTORY_CLASS, BEAN_NAME));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void doesNotResolveInterfaceForNonFactoryClasses() throws Exception {
|
||||
|
||||
processor.setBeanFactory(beanFactory);
|
||||
assertNotTypeDetected(BeanFactory.class);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void doesNotResolveInterfaceForUnloadableClass() throws Exception {
|
||||
|
||||
BeanDefinitionBuilder builder = BeanDefinitionBuilder.rootBeanDefinition(FACTORY_CLASS).addPropertyValue(
|
||||
DAO_INTERFACE_PROPERTY, "com.acme.Foo");
|
||||
|
||||
when(beanFactory.getBeanDefinition(BEAN_NAME)).thenReturn(builder.getBeanDefinition());
|
||||
|
||||
assertNotTypeDetected(FACTORY_CLASS);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void doesNotResolveTypeForPlainBeanFactory() throws Exception {
|
||||
|
||||
BeanFactory beanFactory = mock(BeanFactory.class);
|
||||
processor.setBeanFactory(beanFactory);
|
||||
|
||||
assertNotTypeDetected(FACTORY_CLASS);
|
||||
}
|
||||
|
||||
private void assertNotTypeDetected(Class<?> beanClass) {
|
||||
|
||||
assertThat(processor.predictBeanType(beanClass, BEAN_NAME), is(nullValue()));
|
||||
}
|
||||
|
||||
private class User {
|
||||
|
||||
}
|
||||
|
||||
private interface UserDao extends Repository<User, Long> {
|
||||
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,85 @@
|
||||
/*
|
||||
* Copyright 2008-2010 the original author or authors.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
|
||||
* use this file except in compliance with the License. You may obtain a copy of
|
||||
* the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
|
||||
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
|
||||
* License for the specific language governing permissions and limitations under
|
||||
* the License.
|
||||
*/
|
||||
package org.springframework.data.repository.core.support;
|
||||
|
||||
import static org.mockito.Matchers.anyBoolean;
|
||||
import static org.mockito.Matchers.eq;
|
||||
import static org.mockito.Matchers.isA;
|
||||
import static org.mockito.Mockito.*;
|
||||
|
||||
import java.util.HashMap;
|
||||
import java.util.Map;
|
||||
|
||||
import org.junit.Before;
|
||||
import org.junit.Test;
|
||||
import org.junit.runner.RunWith;
|
||||
import org.mockito.Mock;
|
||||
import org.mockito.runners.MockitoJUnitRunner;
|
||||
import org.springframework.aop.framework.ProxyFactory;
|
||||
import org.springframework.beans.factory.ListableBeanFactory;
|
||||
import org.springframework.dao.support.PersistenceExceptionTranslationInterceptor;
|
||||
import org.springframework.dao.support.PersistenceExceptionTranslator;
|
||||
import org.springframework.data.repository.core.support.RepositoryProxyPostProcessor;
|
||||
import org.springframework.data.repository.core.support.TransactionalRepositoryProxyPostProcessor;
|
||||
import org.springframework.transaction.interceptor.TransactionInterceptor;
|
||||
|
||||
/**
|
||||
* Unit test for {@link TransactionalRepositoryProxyPostProcessor}.
|
||||
*
|
||||
* @author Oliver Gierke
|
||||
*/
|
||||
@RunWith(MockitoJUnitRunner.class)
|
||||
public class TransactionRepositoryProxyPostProcessorUnitTests {
|
||||
|
||||
TransactionalRepositoryProxyPostProcessor processor;
|
||||
|
||||
@Mock
|
||||
ListableBeanFactory beanFactory;
|
||||
@Mock
|
||||
ProxyFactory proxyFactory;
|
||||
|
||||
@Before
|
||||
public void setUp() {
|
||||
|
||||
Map<String, PersistenceExceptionTranslator> beans = new HashMap<String, PersistenceExceptionTranslator>();
|
||||
beans.put("foo", mock(PersistenceExceptionTranslator.class));
|
||||
when(beanFactory.getBeansOfType(eq(PersistenceExceptionTranslator.class), anyBoolean(), anyBoolean())).thenReturn(
|
||||
beans);
|
||||
}
|
||||
|
||||
@Test(expected = IllegalArgumentException.class)
|
||||
public void rejectsNullBeanFactory() throws Exception {
|
||||
|
||||
new TransactionalRepositoryProxyPostProcessor(null, "transactionManager");
|
||||
}
|
||||
|
||||
@Test(expected = IllegalArgumentException.class)
|
||||
public void rejectsNullTxManagerName() throws Exception {
|
||||
|
||||
new TransactionalRepositoryProxyPostProcessor(beanFactory, null);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void setsUpBasicInstance() throws Exception {
|
||||
|
||||
RepositoryProxyPostProcessor postProcessor = new TransactionalRepositoryProxyPostProcessor(beanFactory, "txManager");
|
||||
|
||||
postProcessor.postProcess(proxyFactory);
|
||||
|
||||
verify(proxyFactory).addAdvice(isA(PersistenceExceptionTranslationInterceptor.class));
|
||||
verify(proxyFactory).addAdvice(isA(TransactionInterceptor.class));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,42 @@
|
||||
/*
|
||||
* Copyright 2012 the original author or authors.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
package org.springframework.data.repository.init;
|
||||
|
||||
import static org.hamcrest.Matchers.*;
|
||||
import static org.junit.Assert.*;
|
||||
|
||||
import java.util.Collection;
|
||||
|
||||
import org.junit.Test;
|
||||
import org.springframework.core.io.ClassPathResource;
|
||||
|
||||
/**
|
||||
* Integration tests for {@link JacksonResourceReader}.
|
||||
*
|
||||
* @author Oliver Gierke
|
||||
*/
|
||||
public class JacksonResourceReaderIntegrationTests {
|
||||
|
||||
@Test
|
||||
public void readsFileWithMultipleObjects() throws Exception {
|
||||
|
||||
ResourceReader reader = new JacksonResourceReader();
|
||||
Object result = reader.readFrom(new ClassPathResource("data.json", getClass()), null);
|
||||
|
||||
assertThat(result, is(instanceOf(Collection.class)));
|
||||
assertThat((Collection<?>) result, hasSize(1));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,25 @@
|
||||
/*
|
||||
* Copyright 2012 the original author or authors.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
package org.springframework.data.repository.init;
|
||||
|
||||
/**
|
||||
* @author Oliver Gierke
|
||||
*/
|
||||
public class Person {
|
||||
|
||||
String firstname;
|
||||
String lastname;
|
||||
}
|
||||
@@ -0,0 +1,105 @@
|
||||
/*
|
||||
* Copyright 2012 the original author or authors.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
package org.springframework.data.repository.init;
|
||||
|
||||
import static org.mockito.Matchers.*;
|
||||
import static org.mockito.Mockito.*;
|
||||
|
||||
import java.io.Serializable;
|
||||
import java.util.Collection;
|
||||
import java.util.Collections;
|
||||
|
||||
import org.junit.Test;
|
||||
import org.junit.runner.RunWith;
|
||||
import org.mockito.Mock;
|
||||
import org.mockito.runners.MockitoJUnitRunner;
|
||||
import org.springframework.context.ApplicationEvent;
|
||||
import org.springframework.context.ApplicationEventPublisher;
|
||||
import org.springframework.core.io.Resource;
|
||||
import org.springframework.data.repository.CrudRepository;
|
||||
import org.springframework.data.repository.support.Repositories;
|
||||
|
||||
/**
|
||||
* Unit tests for {@link UnmarshallingRepositoryInitializer}.
|
||||
*
|
||||
* @author Oliver Gierke
|
||||
*/
|
||||
@RunWith(MockitoJUnitRunner.class)
|
||||
public class ResourceReaderRepositoryInitializerUnitTests {
|
||||
|
||||
@Mock
|
||||
ResourceReader reader;
|
||||
@Mock
|
||||
Repositories repositories;
|
||||
@Mock
|
||||
Resource resource;
|
||||
@Mock
|
||||
CrudRepository<Object, Serializable> repo;
|
||||
|
||||
@Mock
|
||||
ApplicationEventPublisher publisher;
|
||||
|
||||
@Test
|
||||
public void storesSingleObjectCorrectly() throws Exception {
|
||||
|
||||
Object reference = new Object();
|
||||
|
||||
setUpReferenceAndInititalize(reference);
|
||||
|
||||
verify(repo, times(1)).save(reference);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void storesCollectionOfObjectsCorrectly() throws Exception {
|
||||
|
||||
Object object = new Object();
|
||||
Collection<Object> reference = Collections.singletonList(object);
|
||||
|
||||
setUpReferenceAndInititalize(reference);
|
||||
|
||||
verify(repo, times(1)).save(object);
|
||||
}
|
||||
|
||||
/**
|
||||
* @see DATACMNS-224
|
||||
*/
|
||||
@Test
|
||||
public void emitsRepositoriesPopulatedEventIfPublisherConfigured() throws Exception {
|
||||
|
||||
RepositoryPopulator populator = setUpReferenceAndInititalize(new Object(), publisher);
|
||||
|
||||
ApplicationEvent event = new RepositoriesPopulatedEvent(populator, repositories);
|
||||
verify(publisher, times(1)).publishEvent(event);
|
||||
}
|
||||
|
||||
private RepositoryPopulator setUpReferenceAndInititalize(Object reference, ApplicationEventPublisher publish)
|
||||
throws Exception {
|
||||
|
||||
when(reader.readFrom(any(Resource.class), any(ClassLoader.class))).thenReturn(reference);
|
||||
when(repositories.getRepositoryFor(Object.class)).thenReturn(repo);
|
||||
|
||||
ResourceReaderRepositoryPopulator populator = new ResourceReaderRepositoryPopulator(reader);
|
||||
populator.setResources(resource);
|
||||
populator.setApplicationEventPublisher(publisher);
|
||||
populator.populate(repositories);
|
||||
|
||||
return populator;
|
||||
}
|
||||
|
||||
private RepositoryPopulator setUpReferenceAndInititalize(Object reference) throws Exception {
|
||||
return setUpReferenceAndInititalize(reference, null);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,74 @@
|
||||
/*
|
||||
* Copyright 2011 the original author or authors.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
package org.springframework.data.repository.query;
|
||||
|
||||
import static org.hamcrest.CoreMatchers.*;
|
||||
import static org.junit.Assert.*;
|
||||
|
||||
import java.lang.reflect.Method;
|
||||
import java.util.Iterator;
|
||||
|
||||
import org.junit.Before;
|
||||
import org.junit.Test;
|
||||
import org.springframework.data.domain.Pageable;
|
||||
|
||||
/**
|
||||
* Unit tests for {@link ParametersParameterAccessor}.
|
||||
*
|
||||
* @author Oliver Gierke
|
||||
*/
|
||||
public class ParametersParameterAccessorUnitTests {
|
||||
|
||||
Parameters parameters;
|
||||
|
||||
@Before
|
||||
public void setUp() throws Exception {
|
||||
parameters = new Parameters(Sample.class.getMethod("method", String.class, int.class));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void accessorIteratorHasNext() throws SecurityException, NoSuchMethodException {
|
||||
|
||||
ParameterAccessor accessor = new ParametersParameterAccessor(parameters, new Object[] { "Foo", 2 });
|
||||
|
||||
Iterator<Object> iterator = accessor.iterator();
|
||||
assertThat(iterator.hasNext(), is(true));
|
||||
assertThat(iterator.next(), is((Object) "Foo"));
|
||||
assertThat(iterator.hasNext(), is(true));
|
||||
assertThat(iterator.next(), is((Object) 2));
|
||||
assertThat(iterator.hasNext(), is(false));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void detectsNullValue() throws Exception {
|
||||
|
||||
ParameterAccessor accessor = new ParametersParameterAccessor(parameters, new Object[] { null, 5 });
|
||||
assertThat(accessor.hasBindableNullValue(), is(true));
|
||||
|
||||
Method method = Sample.class.getMethod("method", Pageable.class, String.class);
|
||||
Parameters parameters = new Parameters(method);
|
||||
|
||||
accessor = new ParametersParameterAccessor(parameters, new Object[] { null, "Foo" });
|
||||
assertThat(accessor.hasBindableNullValue(), is(false));
|
||||
}
|
||||
|
||||
interface Sample {
|
||||
|
||||
void method(String string, int integer);
|
||||
|
||||
void method(Pageable pageable, String string);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,147 @@
|
||||
/*
|
||||
* Copyright 2008-2010 the original author or authors.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
|
||||
* use this file except in compliance with the License. You may obtain a copy of
|
||||
* the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
|
||||
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
|
||||
* License for the specific language governing permissions and limitations under
|
||||
* the License.
|
||||
*/
|
||||
package org.springframework.data.repository.query;
|
||||
|
||||
import static org.hamcrest.CoreMatchers.*;
|
||||
import static org.junit.Assert.*;
|
||||
|
||||
import java.lang.reflect.Method;
|
||||
|
||||
import org.junit.Before;
|
||||
import org.junit.Test;
|
||||
import org.springframework.data.domain.Pageable;
|
||||
import org.springframework.data.domain.Sort;
|
||||
|
||||
/**
|
||||
* Unit test for {@link Parameters}.
|
||||
*
|
||||
* @author Oliver Gierke
|
||||
*/
|
||||
public class ParametersUnitTests {
|
||||
|
||||
private Method valid;
|
||||
|
||||
@Before
|
||||
public void setUp() throws SecurityException, NoSuchMethodException {
|
||||
|
||||
valid = SampleDao.class.getMethod("valid", String.class);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void checksValidMethodCorrectly() throws Exception {
|
||||
|
||||
Method validWithPageable = SampleDao.class.getMethod("validWithPageable", String.class, Pageable.class);
|
||||
Method validWithSort = SampleDao.class.getMethod("validWithSort", String.class, Sort.class);
|
||||
|
||||
new Parameters(valid);
|
||||
new Parameters(validWithPageable);
|
||||
new Parameters(validWithSort);
|
||||
}
|
||||
|
||||
@Test(expected = IllegalArgumentException.class)
|
||||
public void rejectsInvalidMethodWithParamMissing() throws Exception {
|
||||
|
||||
Method method = SampleDao.class.getMethod("invalidParamMissing", String.class, String.class);
|
||||
new Parameters(method);
|
||||
}
|
||||
|
||||
@Test(expected = IllegalArgumentException.class)
|
||||
public void rejectsNullMethod() throws Exception {
|
||||
|
||||
new Parameters(null);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void detectsNamedParameterCorrectly() throws Exception {
|
||||
|
||||
Parameters parameters = getParametersFor("validWithSort", String.class, Sort.class);
|
||||
|
||||
Parameter parameter = parameters.getParameter(0);
|
||||
|
||||
assertThat(parameter.isNamedParameter(), is(true));
|
||||
assertThat(parameter.getPlaceholder(), is(":username"));
|
||||
|
||||
parameter = parameters.getParameter(1);
|
||||
|
||||
assertThat(parameter.isNamedParameter(), is(false));
|
||||
assertThat(parameter.isSpecialParameter(), is(true));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void calculatesPlaceholderPositionCorrectly() throws Exception {
|
||||
|
||||
Method method = SampleDao.class.getMethod("validWithSortFirst", Sort.class, String.class);
|
||||
|
||||
Parameters parameters = new Parameters(method);
|
||||
assertThat(parameters.getBindableParameter(0).getIndex(), is(1));
|
||||
|
||||
method = SampleDao.class.getMethod("validWithSortInBetween", String.class, Sort.class, String.class);
|
||||
|
||||
parameters = new Parameters(method);
|
||||
|
||||
assertThat(parameters.getBindableParameter(0).getIndex(), is(0));
|
||||
assertThat(parameters.getBindableParameter(1).getIndex(), is(2));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void detectsEmptyParameterListCorrectly() throws Exception {
|
||||
|
||||
Parameters parameters = getParametersFor("emptyParameters");
|
||||
assertThat(parameters.hasParameterAt(0), is(false));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void detectsPageableParameter() throws Exception {
|
||||
Parameters parameters = getParametersFor("validWithPageable", String.class, Pageable.class);
|
||||
assertThat(parameters.getPageableIndex(), is(1));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void detectsSortParameter() throws Exception {
|
||||
Parameters parameters = getParametersFor("validWithSort", String.class, Sort.class);
|
||||
assertThat(parameters.getSortIndex(), is(1));
|
||||
}
|
||||
|
||||
private Parameters getParametersFor(String methodName, Class<?>... parameterTypes) throws SecurityException,
|
||||
NoSuchMethodException {
|
||||
|
||||
Method method = SampleDao.class.getMethod(methodName, parameterTypes);
|
||||
|
||||
return new Parameters(method);
|
||||
}
|
||||
|
||||
static class User {
|
||||
|
||||
}
|
||||
|
||||
static interface SampleDao {
|
||||
|
||||
User valid(@Param("username") String username);
|
||||
|
||||
User invalidParamMissing(@Param("username") String username, String lastname);
|
||||
|
||||
User validWithPageable(@Param("username") String username, Pageable pageable);
|
||||
|
||||
User validWithSort(@Param("username") String username, Sort sort);
|
||||
|
||||
User validWithSortFirst(Sort sort, String username);
|
||||
|
||||
User validWithSortInBetween(String firstname, Sort sort, String lastname);
|
||||
|
||||
User emptyParameters();
|
||||
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,127 @@
|
||||
/*
|
||||
* Copyright 2008-2011 the original author or authors.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
package org.springframework.data.repository.query;
|
||||
|
||||
import static org.junit.Assert.*;
|
||||
import static org.mockito.Mockito.*;
|
||||
import static org.hamcrest.CoreMatchers.*;
|
||||
|
||||
import java.lang.reflect.Method;
|
||||
|
||||
import org.junit.Test;
|
||||
import org.junit.runner.RunWith;
|
||||
import org.mockito.Mock;
|
||||
import org.mockito.Mockito;
|
||||
import org.mockito.runners.MockitoJUnitRunner;
|
||||
import org.springframework.data.domain.Page;
|
||||
import org.springframework.data.domain.Pageable;
|
||||
import org.springframework.data.repository.core.RepositoryMetadata;
|
||||
|
||||
/**
|
||||
* Unit tests for {@link QueryMethod}.
|
||||
*
|
||||
* @author Oliver Gierke
|
||||
*/
|
||||
@RunWith(MockitoJUnitRunner.class)
|
||||
public class QueryMethodUnitTests {
|
||||
|
||||
@Mock
|
||||
RepositoryMetadata metadata;
|
||||
|
||||
@Test(expected = IllegalStateException.class)
|
||||
public void rejectsPagingMethodWithInvalidReturnType() throws Exception {
|
||||
|
||||
Method method = SampleRepository.class.getMethod("pagingMethodWithInvalidReturnType", Pageable.class);
|
||||
new QueryMethod(method, metadata);
|
||||
}
|
||||
|
||||
@Test(expected = IllegalArgumentException.class)
|
||||
public void rejectsPagingMethodWithoutPageable() throws Exception {
|
||||
Method method = SampleRepository.class.getMethod("pagingMethodWithoutPageable");
|
||||
new QueryMethod(method, metadata);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void setsUpSimpleQueryMethodCorrectly() throws Exception {
|
||||
Method method = SampleRepository.class.getMethod("findByUsername", String.class);
|
||||
new QueryMethod(method, metadata);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void considersIterableMethodForCollectionQuery() throws Exception {
|
||||
Method method = SampleRepository.class.getMethod("sampleMethod");
|
||||
QueryMethod queryMethod = new QueryMethod(method, metadata);
|
||||
assertThat(queryMethod.isCollectionQuery(), is(true));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void doesNotConsiderPageMethodCollectionQuery() throws Exception {
|
||||
Method method = SampleRepository.class.getMethod("anotherSampleMethod", Pageable.class);
|
||||
QueryMethod queryMethod = new QueryMethod(method, metadata);
|
||||
assertThat(queryMethod.isPageQuery(), is(true));
|
||||
assertThat(queryMethod.isCollectionQuery(), is(false));
|
||||
}
|
||||
|
||||
@Test
|
||||
@SuppressWarnings({ "unchecked", "rawtypes" })
|
||||
public void detectsAnEntityBeingReturned() throws Exception {
|
||||
|
||||
when(metadata.getDomainType()).thenReturn((Class) User.class);
|
||||
when(metadata.getReturnedDomainClass(Mockito.any(Method.class))).thenReturn((Class) SpecialUser.class);
|
||||
|
||||
Method method = SampleRepository.class.getMethod("returnsEntitySubclass");
|
||||
QueryMethod queryMethod = new QueryMethod(method, metadata);
|
||||
|
||||
assertThat(queryMethod.isQueryForEntity(), is(true));
|
||||
}
|
||||
|
||||
@Test
|
||||
@SuppressWarnings({ "unchecked", "rawtypes" })
|
||||
public void detectsNonEntityBeingReturned() throws Exception {
|
||||
|
||||
when(metadata.getDomainType()).thenReturn((Class) User.class);
|
||||
when(metadata.getReturnedDomainClass(Mockito.any(Method.class))).thenReturn((Class) Integer.class);
|
||||
|
||||
Method method = SampleRepository.class.getMethod("returnsProjection");
|
||||
QueryMethod queryMethod = new QueryMethod(method, metadata);
|
||||
|
||||
assertThat(queryMethod.isQueryForEntity(), is(false));
|
||||
}
|
||||
|
||||
interface SampleRepository {
|
||||
String pagingMethodWithInvalidReturnType(Pageable pageable);
|
||||
|
||||
Page<String> pagingMethodWithoutPageable();
|
||||
|
||||
String findByUsername(String username);
|
||||
|
||||
Iterable<String> sampleMethod();
|
||||
|
||||
Page<String> anotherSampleMethod(Pageable pageable);
|
||||
|
||||
SpecialUser returnsEntitySubclass();
|
||||
|
||||
Integer returnsProjection();
|
||||
}
|
||||
|
||||
class User {
|
||||
|
||||
}
|
||||
|
||||
class SpecialUser extends User {
|
||||
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,118 @@
|
||||
/*
|
||||
* Copyright 2008-2010 the original author or authors.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
|
||||
* use this file except in compliance with the License. You may obtain a copy of
|
||||
* the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
|
||||
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
|
||||
* License for the specific language governing permissions and limitations under
|
||||
* the License.
|
||||
*/
|
||||
package org.springframework.data.repository.query;
|
||||
|
||||
import static org.hamcrest.CoreMatchers.*;
|
||||
import static org.junit.Assert.*;
|
||||
|
||||
import org.junit.Before;
|
||||
import org.junit.Test;
|
||||
import org.springframework.data.domain.PageRequest;
|
||||
import org.springframework.data.domain.Pageable;
|
||||
import org.springframework.data.domain.Sort;
|
||||
|
||||
/**
|
||||
* Unit tests for {@link ParametersParameterAccessor}.
|
||||
*
|
||||
* @author Oliver Gierke
|
||||
*/
|
||||
public class SimpleParameterAccessorUnitTests {
|
||||
|
||||
Parameters parameters, sortParameters, pageableParameters;
|
||||
|
||||
@Before
|
||||
public void setUp() throws SecurityException, NoSuchMethodException {
|
||||
|
||||
parameters = new Parameters(Sample.class.getMethod("sample", String.class));
|
||||
sortParameters = new Parameters(Sample.class.getMethod("sample1", String.class, Sort.class));
|
||||
pageableParameters = new Parameters(Sample.class.getMethod("sample2", String.class, Pageable.class));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testname() throws Exception {
|
||||
|
||||
new ParametersParameterAccessor(parameters, new Object[] { "test" });
|
||||
}
|
||||
|
||||
@Test(expected = IllegalArgumentException.class)
|
||||
public void rejectsNullParameters() throws Exception {
|
||||
|
||||
new ParametersParameterAccessor(null, new Object[0]);
|
||||
}
|
||||
|
||||
@Test(expected = IllegalArgumentException.class)
|
||||
public void rejectsNullValues() throws Exception {
|
||||
|
||||
new ParametersParameterAccessor(parameters, null);
|
||||
}
|
||||
|
||||
@Test(expected = IllegalArgumentException.class)
|
||||
public void rejectsTooLittleNumberOfArguments() throws Exception {
|
||||
|
||||
new ParametersParameterAccessor(parameters, new Object[0]);
|
||||
}
|
||||
|
||||
@Test(expected = IllegalArgumentException.class)
|
||||
public void rejectsTooManyArguments() throws Exception {
|
||||
|
||||
new ParametersParameterAccessor(parameters, new Object[] { "test", "test" });
|
||||
}
|
||||
|
||||
@Test
|
||||
public void returnsNullForPageableAndSortIfNoneAvailable() throws Exception {
|
||||
|
||||
ParameterAccessor accessor = new ParametersParameterAccessor(parameters, new Object[] { "test" });
|
||||
assertThat(accessor.getPageable(), is(nullValue()));
|
||||
assertThat(accessor.getSort(), is(nullValue()));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void returnsSortIfAvailable() {
|
||||
|
||||
Sort sort = new Sort("foo");
|
||||
ParameterAccessor accessor = new ParametersParameterAccessor(sortParameters, new Object[] { "test", sort });
|
||||
assertThat(accessor.getSort(), is(sort));
|
||||
assertThat(accessor.getPageable(), is(nullValue()));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void returnsPageableIfAvailable() {
|
||||
|
||||
Pageable pageable = new PageRequest(0, 10);
|
||||
ParameterAccessor accessor = new ParametersParameterAccessor(pageableParameters, new Object[] { "test", pageable });
|
||||
assertThat(accessor.getPageable(), is(pageable));
|
||||
assertThat(accessor.getSort(), is(nullValue()));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void returnsSortFromPageableIfAvailable() throws Exception {
|
||||
|
||||
Sort sort = new Sort("foo");
|
||||
Pageable pageable = new PageRequest(0, 10, sort);
|
||||
ParameterAccessor accessor = new ParametersParameterAccessor(pageableParameters, new Object[] { "test", pageable });
|
||||
assertThat(accessor.getPageable(), is(pageable));
|
||||
assertThat(accessor.getSort(), is(sort));
|
||||
}
|
||||
|
||||
interface Sample {
|
||||
|
||||
void sample(String firstname);
|
||||
|
||||
void sample1(String firstname, Sort sort);
|
||||
|
||||
void sample2(String firstname, Pageable pageable);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,77 @@
|
||||
/*
|
||||
* Copyright 2008-2010 the original author or authors.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
package org.springframework.data.repository.query.parser;
|
||||
|
||||
import static org.hamcrest.Matchers.*;
|
||||
import static org.junit.Assert.*;
|
||||
import static org.springframework.data.domain.Sort.Direction.*;
|
||||
|
||||
import org.junit.Test;
|
||||
import org.springframework.data.domain.Sort;
|
||||
import org.springframework.data.domain.Sort.Order;
|
||||
|
||||
/**
|
||||
* Unit test for {@link OrderBySource}.
|
||||
*
|
||||
* @author Oliver Gierke
|
||||
*/
|
||||
public class OrderBySourceUnitTests {
|
||||
|
||||
@Test
|
||||
public void handlesSingleDirectionAndPropertyCorrectly() throws Exception {
|
||||
|
||||
assertThat(new OrderBySource("UsernameDesc").toSort(), is(new Sort(DESC, "username")));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void handlesCamelCasePropertyCorrecty() throws Exception {
|
||||
|
||||
assertThat(new OrderBySource("LastnameUsernameDesc").toSort(), is(new Sort(DESC, "lastnameUsername")));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void handlesMultipleDirectionsCorrectly() throws Exception {
|
||||
|
||||
OrderBySource orderBySource = new OrderBySource("LastnameAscUsernameDesc");
|
||||
assertThat(orderBySource.toSort(), is(new Sort(new Order(ASC, "lastname"), new Order(DESC, "username"))));
|
||||
}
|
||||
|
||||
@Test(expected = IllegalArgumentException.class)
|
||||
public void rejectsMissingProperty() throws Exception {
|
||||
|
||||
new OrderBySource("Desc");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void usesNestedPropertyCorrectly() throws Exception {
|
||||
|
||||
OrderBySource source = new OrderBySource("BarNameDesc", Foo.class);
|
||||
assertThat(source.toSort(), is(new Sort(new Order(DESC, "bar.name"))));
|
||||
|
||||
}
|
||||
|
||||
@SuppressWarnings("unused")
|
||||
private class Foo {
|
||||
|
||||
private Bar bar;
|
||||
}
|
||||
|
||||
@SuppressWarnings("unused")
|
||||
private class Bar {
|
||||
|
||||
private String name;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,399 @@
|
||||
/*
|
||||
* Copyright 2008-2010 the original author or authors.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
|
||||
* use this file except in compliance with the License. You may obtain a copy of
|
||||
* the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
|
||||
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
|
||||
* License for the specific language governing permissions and limitations under
|
||||
* the License.
|
||||
*/
|
||||
package org.springframework.data.repository.query.parser;
|
||||
|
||||
import static java.util.Arrays.*;
|
||||
import static org.hamcrest.Matchers.*;
|
||||
import static org.junit.Assert.*;
|
||||
import static org.springframework.data.repository.query.parser.Part.Type.*;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.Arrays;
|
||||
import java.util.Collection;
|
||||
import java.util.Date;
|
||||
import java.util.Iterator;
|
||||
import java.util.List;
|
||||
|
||||
import org.junit.Test;
|
||||
import org.springframework.data.domain.Sort;
|
||||
import org.springframework.data.domain.Sort.Direction;
|
||||
import org.springframework.data.mapping.PropertyPath;
|
||||
import org.springframework.data.repository.query.parser.Part.IgnoreCaseType;
|
||||
import org.springframework.data.repository.query.parser.Part.Type;
|
||||
import org.springframework.data.repository.query.parser.PartTree.OrPart;
|
||||
|
||||
/**
|
||||
* Unit tests for {@link PartTree}.
|
||||
*
|
||||
* @author Oliver Gierke
|
||||
* @author Phillip Webb
|
||||
*/
|
||||
public class PartTreeUnitTests {
|
||||
|
||||
private String[] PREFIXES = { "find", "read", "get" };
|
||||
|
||||
@Test(expected = IllegalArgumentException.class)
|
||||
public void rejectsNullSource() throws Exception {
|
||||
new PartTree(null, getClass());
|
||||
}
|
||||
|
||||
@Test(expected = IllegalArgumentException.class)
|
||||
public void rejectsNullDomainClass() throws Exception {
|
||||
new PartTree("test", null);
|
||||
}
|
||||
|
||||
@Test(expected = IllegalArgumentException.class)
|
||||
public void rejectsMultipleOrderBy() throws Exception {
|
||||
partTree("firstnameOrderByLastnameOrderByFirstname");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void parsesSimplePropertyCorrectly() throws Exception {
|
||||
PartTree partTree = partTree("firstname");
|
||||
assertPart(partTree, parts("firstname"));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void parsesAndPropertiesCorrectly() throws Exception {
|
||||
PartTree partTree = partTree("firstnameAndLastname");
|
||||
assertPart(partTree, parts("firstname", "lastname"));
|
||||
assertThat(partTree.getSort(), is(nullValue()));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void parsesOrPropertiesCorrectly() throws Exception {
|
||||
PartTree partTree = partTree("firstnameOrLastname");
|
||||
assertPart(partTree, parts("firstname"), parts("lastname"));
|
||||
assertThat(partTree.getSort(), is(nullValue()));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void parsesCombinedAndAndOrPropertiesCorrectly() throws Exception {
|
||||
PartTree tree = partTree("firstnameAndLastnameOrLastname");
|
||||
assertPart(tree, parts("firstname", "lastname"), parts("lastname"));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void hasSortIfOrderByIsGiven() throws Exception {
|
||||
PartTree partTree = partTree("firstnameOrderByLastnameDesc");
|
||||
assertThat(partTree.getSort(), is(new Sort(Direction.DESC, "lastname")));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void hasSortIfOrderByIsGivenWithAllIgnoreCase() throws Exception {
|
||||
hasSortIfOrderByIsGivenWithAllIgnoreCase("firstnameOrderByLastnameDescAllIgnoreCase");
|
||||
hasSortIfOrderByIsGivenWithAllIgnoreCase("firstnameOrderByLastnameDescAllIgnoringCase");
|
||||
hasSortIfOrderByIsGivenWithAllIgnoreCase("firstnameAllIgnoreCaseOrderByLastnameDesc");
|
||||
}
|
||||
|
||||
private void hasSortIfOrderByIsGivenWithAllIgnoreCase(String source) throws Exception {
|
||||
PartTree partTree = partTree(source);
|
||||
assertThat(partTree.getSort(), is(new Sort(Direction.DESC, "lastname")));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void detectsDistinctCorrectly() throws Exception {
|
||||
for (String prefix : PREFIXES) {
|
||||
detectsDistinctCorrectly(prefix + "DistinctByLastname", true);
|
||||
detectsDistinctCorrectly(prefix + "UsersDistinctByLastname", true);
|
||||
detectsDistinctCorrectly(prefix + "DistinctUsersByLastname", true);
|
||||
detectsDistinctCorrectly(prefix + "UsersByLastname", false);
|
||||
detectsDistinctCorrectly(prefix + "ByLastname", false);
|
||||
// Check it's non-greedy (would strip everything until Order*By*
|
||||
// otherwise)
|
||||
PartTree tree = detectsDistinctCorrectly(prefix + "ByLastnameOrderByFirstnameDesc", false);
|
||||
assertThat(tree.getSort(), is(new Sort(Direction.DESC, "firstname")));
|
||||
}
|
||||
}
|
||||
|
||||
private PartTree detectsDistinctCorrectly(String source, boolean expected) {
|
||||
PartTree tree = partTree(source);
|
||||
assertThat("Unexpected distinct value for '" + source + "'", tree.isDistinct(), is(expected));
|
||||
return tree;
|
||||
}
|
||||
|
||||
@Test
|
||||
public void parsesWithinCorrectly() {
|
||||
PartTree tree = partTree("findByLocationWithin");
|
||||
for (Part part : tree.getParts()) {
|
||||
assertThat(part.getType(), is(Type.WITHIN));
|
||||
assertThat(part.getProperty(), is(newProperty("location")));
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
public void parsesNearCorrectly() {
|
||||
assertType(asList("locationNear"), NEAR, "location");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void supportToStringWithoutSortOrder() throws Exception {
|
||||
assertType(asList("firstname"), SIMPLE_PROPERTY, "firstname");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void supportToStringWithSortOrder() throws Exception {
|
||||
PartTree tree = partTree("firstnameOrderByLastnameDesc");
|
||||
assertThat(tree.toString(), is(equalTo("firstname SIMPLE_PROPERTY Order By lastname: DESC")));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void detectsIgnoreAllCase() throws Exception {
|
||||
detectsIgnoreAllCase("firstnameOrderByLastnameDescAllIgnoreCase", IgnoreCaseType.WHEN_POSSIBLE);
|
||||
detectsIgnoreAllCase("firstnameOrderByLastnameDescAllIgnoringCase", IgnoreCaseType.WHEN_POSSIBLE);
|
||||
detectsIgnoreAllCase("firstnameAllIgnoreCaseOrderByLastnameDesc", IgnoreCaseType.WHEN_POSSIBLE);
|
||||
detectsIgnoreAllCase("getByFirstnameAllIgnoreCase", IgnoreCaseType.WHEN_POSSIBLE);
|
||||
detectsIgnoreAllCase("getByFirstname", IgnoreCaseType.NEVER);
|
||||
detectsIgnoreAllCase("firstnameOrderByLastnameDesc", IgnoreCaseType.NEVER);
|
||||
}
|
||||
|
||||
private void detectsIgnoreAllCase(String source, IgnoreCaseType expected) throws Exception {
|
||||
PartTree tree = partTree(source);
|
||||
for (Part part : tree.getParts()) {
|
||||
assertThat(part.shouldIgnoreCase(), is(expected));
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
public void detectsSpecificIgnoreCase() throws Exception {
|
||||
PartTree tree = partTree("findByFirstnameIgnoreCaseAndLastname");
|
||||
assertPart(tree, parts("firstname", "lastname"));
|
||||
Iterator<Part> parts = tree.getParts().iterator();
|
||||
assertThat(parts.next().shouldIgnoreCase(), is(IgnoreCaseType.ALWAYS));
|
||||
assertThat(parts.next().shouldIgnoreCase(), is(IgnoreCaseType.NEVER));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void detectsSpecificIgnoringCase() throws Exception {
|
||||
PartTree tree = partTree("findByFirstnameIgnoringCaseAndLastname");
|
||||
assertPart(tree, parts("firstname", "lastname"));
|
||||
Iterator<Part> parts = tree.getParts().iterator();
|
||||
assertThat(parts.next().shouldIgnoreCase(), is(IgnoreCaseType.ALWAYS));
|
||||
assertThat(parts.next().shouldIgnoreCase(), is(IgnoreCaseType.NEVER));
|
||||
}
|
||||
|
||||
/**
|
||||
* @see DATACMNS-78
|
||||
*/
|
||||
@Test
|
||||
public void parsesLessThanEqualCorrectly() {
|
||||
assertType(Arrays.asList("lastnameLessThanEqual", "lastnameIsLessThanEqual"), LESS_THAN_EQUAL, "lastname");
|
||||
}
|
||||
|
||||
/**
|
||||
* @see DATACMNS-78
|
||||
*/
|
||||
@Test
|
||||
public void parsesGreaterThanEqualCorrectly() {
|
||||
assertType(Arrays.asList("lastnameGreaterThanEqual", "lastnameIsGreaterThanEqual"), GREATER_THAN_EQUAL, "lastname");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void returnsAllParts() {
|
||||
|
||||
PartTree tree = partTree("findByLastnameAndFirstname");
|
||||
assertPart(tree, parts("lastname", "firstname"));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void returnsAllPartsOfType() {
|
||||
|
||||
PartTree tree = partTree("findByLastnameAndFirstnameGreaterThan");
|
||||
|
||||
Collection<Part> parts = toCollection(tree.getParts(Type.SIMPLE_PROPERTY));
|
||||
assertThat(parts, hasItem(part("lastname")));
|
||||
assertThat(parts, is(hasSize(1)));
|
||||
|
||||
parts = toCollection(tree.getParts(Type.GREATER_THAN));
|
||||
assertThat(parts, hasItem(new Part("FirstnameGreaterThan", User.class)));
|
||||
assertThat(parts, is(hasSize(1)));
|
||||
}
|
||||
|
||||
/**
|
||||
* @see DATACMNS-94
|
||||
*/
|
||||
@Test
|
||||
public void parsesExistsKeywordCorrectly() {
|
||||
assertType(asList("lastnameExists"), EXISTS, "lastname", 0, false);
|
||||
}
|
||||
|
||||
/**
|
||||
* @see DATACMNS-94
|
||||
*/
|
||||
@Test
|
||||
public void parsesRegexKeywordCorrectly() {
|
||||
assertType(asList("lastnameRegex", "lastnameMatchesRegex", "lastnameMatches"), REGEX, "lastname");
|
||||
}
|
||||
|
||||
/**
|
||||
* @see DATACMNS-107
|
||||
*/
|
||||
@Test
|
||||
public void parsesTrueKeywordCorrectly() {
|
||||
assertType(asList("activeTrue", "activeIsTrue"), TRUE, "active", 0, false);
|
||||
}
|
||||
|
||||
/**
|
||||
* @see DATACMNS-107
|
||||
*/
|
||||
@Test
|
||||
public void parsesFalseKeywordCorrectly() {
|
||||
assertType(asList("activeFalse", "activeIsFalse"), FALSE, "active", 0, false);
|
||||
}
|
||||
|
||||
/**
|
||||
* @see DATACMNS-111
|
||||
*/
|
||||
@Test
|
||||
public void parsesStartingWithKeywordCorrectly() {
|
||||
assertType(asList("firstnameStartsWith", "firstnameStartingWith", "firstnameIsStartingWith"), STARTING_WITH,
|
||||
"firstname");
|
||||
}
|
||||
|
||||
/**
|
||||
* @see DATACMNS-111
|
||||
*/
|
||||
@Test
|
||||
public void parsesEndingWithKeywordCorrectly() {
|
||||
assertType(asList("firstnameEndsWith", "firstnameEndingWith", "firstnameIsEndingWith"), ENDING_WITH, "firstname");
|
||||
}
|
||||
|
||||
/**
|
||||
* @see DATACMNS-111
|
||||
*/
|
||||
@Test
|
||||
public void parsesContainingKeywordCorrectly() {
|
||||
assertType(asList("firstnameIsContaining", "firstnameContains", "firstnameContaining"), CONTAINING, "firstname");
|
||||
}
|
||||
|
||||
/**
|
||||
* @see DATACMNS-141
|
||||
*/
|
||||
@Test
|
||||
public void parsesAfterKeywordCorrectly() {
|
||||
assertType(asList("birthdayAfter", "birthdayIsAfter"), Type.AFTER, "birthday");
|
||||
}
|
||||
|
||||
/**
|
||||
* @see DATACMNS-141
|
||||
*/
|
||||
@Test
|
||||
public void parsesBeforeKeywordCorrectly() {
|
||||
assertType(Arrays.asList("birthdayBefore", "birthdayIsBefore"), Type.BEFORE, "birthday");
|
||||
}
|
||||
|
||||
/**
|
||||
* @see DATACMNS-182
|
||||
*/
|
||||
@Test
|
||||
public void parsesContainingCorrectly() {
|
||||
|
||||
PartTree tree = new PartTree("findAllByLegalNameContainingOrCommonNameContainingAllIgnoringCase",
|
||||
Organization.class);
|
||||
assertPart(tree, new Part[] { new Part("legalNameContaining", Organization.class) }, new Part[] { new Part(
|
||||
"commonNameContaining", Organization.class) });
|
||||
}
|
||||
|
||||
/**
|
||||
* @see DATACMNS-221
|
||||
*/
|
||||
@Test
|
||||
public void parsesSpecialCharactersCorrectly() {
|
||||
PartTree tree = new PartTree("findByØreAndÅrOrderByÅrAsc", DomainObjectWithSpecialChars.class);
|
||||
assertPart(tree, new Part[] { new Part("øre", DomainObjectWithSpecialChars.class),
|
||||
new Part("år", DomainObjectWithSpecialChars.class) });
|
||||
assertTrue(tree.getSort().getOrderFor("år").isAscending());
|
||||
}
|
||||
|
||||
private static void assertType(Iterable<String> sources, Type type, String property) {
|
||||
assertType(sources, type, property, 1, true);
|
||||
}
|
||||
|
||||
private static void assertType(Iterable<String> sources, Type type, String property, int numberOfArguments,
|
||||
boolean parameterRequired) {
|
||||
|
||||
for (String source : sources) {
|
||||
Part part = part(source);
|
||||
assertThat(part.getType(), is(type));
|
||||
assertThat(part.getProperty(), is(newProperty(property)));
|
||||
assertThat(part.getNumberOfArguments(), is(numberOfArguments));
|
||||
assertThat(part.getParameterRequired(), is(parameterRequired));
|
||||
}
|
||||
}
|
||||
|
||||
private static PartTree partTree(String source) {
|
||||
return new PartTree(source, User.class);
|
||||
}
|
||||
|
||||
private static Part part(String part) {
|
||||
return new Part(part, User.class);
|
||||
}
|
||||
|
||||
private static Part[] parts(String... part) {
|
||||
Part[] parts = new Part[part.length];
|
||||
for (int i = 0; i < parts.length; i++) {
|
||||
parts[i] = part(part[i]);
|
||||
}
|
||||
return parts;
|
||||
}
|
||||
|
||||
private static PropertyPath newProperty(String name) {
|
||||
return PropertyPath.from(name, User.class);
|
||||
}
|
||||
|
||||
private void assertPart(PartTree tree, Part[]... parts) {
|
||||
Iterator<OrPart> iterator = tree.iterator();
|
||||
for (Part[] part : parts) {
|
||||
assertThat(iterator.hasNext(), is(true));
|
||||
Iterator<Part> partIterator = iterator.next().iterator();
|
||||
for (int k = 0; k < part.length; k++) {
|
||||
assertThat(String.format("Expected %d parts but have %d", part.length, k), partIterator.hasNext(), is(true));
|
||||
Part next = partIterator.next();
|
||||
assertThat(String.format("Expected %s but got %s!", part[k], next), part[k], is(next));
|
||||
}
|
||||
assertThat("Too many parts!", partIterator.hasNext(), is(false));
|
||||
}
|
||||
assertThat("Too many or parts!", iterator.hasNext(), is(false));
|
||||
}
|
||||
|
||||
private static <T> Collection<T> toCollection(Iterable<T> iterable) {
|
||||
|
||||
List<T> result = new ArrayList<T>();
|
||||
for (T element : iterable) {
|
||||
result.add(element);
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
class User {
|
||||
String firstname;
|
||||
String lastname;
|
||||
double[] location;
|
||||
boolean active;
|
||||
Date birthday;
|
||||
}
|
||||
|
||||
class Organization {
|
||||
|
||||
String commonName;
|
||||
String legalName;
|
||||
}
|
||||
|
||||
class DomainObjectWithSpecialChars {
|
||||
String øre;
|
||||
String år;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,30 @@
|
||||
/*
|
||||
* Copyright 2011 the original author or authors.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
package org.springframework.data.repository.sample;
|
||||
|
||||
import java.io.Serializable;
|
||||
|
||||
import org.springframework.data.repository.RepositoryDefinition;
|
||||
|
||||
/**
|
||||
* Sample interface for annotation based repository declaration.
|
||||
*
|
||||
* @author Oliver Gierke
|
||||
*/
|
||||
@RepositoryDefinition(domainClass = Object.class, idClass = Serializable.class)
|
||||
public interface SampleAnnotatedRepository {
|
||||
|
||||
}
|
||||
@@ -0,0 +1,108 @@
|
||||
/*
|
||||
* Copyright 2012 the original author or authors.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
package org.springframework.data.repository.support;
|
||||
|
||||
import static org.hamcrest.Matchers.*;
|
||||
import static org.junit.Assert.*;
|
||||
import static org.mockito.Mockito.*;
|
||||
|
||||
import java.io.Serializable;
|
||||
|
||||
import org.junit.Test;
|
||||
import org.junit.runner.RunWith;
|
||||
import org.mockito.Mock;
|
||||
import org.mockito.runners.MockitoJUnitRunner;
|
||||
import org.springframework.beans.BeanWrapper;
|
||||
import org.springframework.beans.BeanWrapperImpl;
|
||||
import org.springframework.beans.factory.config.InstantiationAwareBeanPostProcessorAdapter;
|
||||
import org.springframework.beans.factory.support.DefaultListableBeanFactory;
|
||||
import org.springframework.beans.factory.support.RootBeanDefinition;
|
||||
import org.springframework.context.support.GenericApplicationContext;
|
||||
import org.springframework.core.convert.TypeDescriptor;
|
||||
import org.springframework.core.convert.support.DefaultConversionService;
|
||||
import org.springframework.data.repository.CrudRepository;
|
||||
import org.springframework.data.repository.core.EntityInformation;
|
||||
import org.springframework.data.repository.core.RepositoryInformation;
|
||||
import org.springframework.data.repository.core.support.DummyEntityInformation;
|
||||
import org.springframework.data.repository.core.support.RepositoryFactoryBeanSupport;
|
||||
import org.springframework.data.repository.core.support.RepositoryFactoryInformation;
|
||||
|
||||
/**
|
||||
* Integration test for {@link DomainClassConverter}.
|
||||
*
|
||||
* @author Oliver Gierke
|
||||
*/
|
||||
@RunWith(MockitoJUnitRunner.class)
|
||||
public class DomainClassConverterIntegrationTests {
|
||||
|
||||
@Mock
|
||||
@SuppressWarnings("rawtypes")
|
||||
RepositoryFactoryBeanSupport factory;
|
||||
@Mock
|
||||
PersonRepository repository;
|
||||
@Mock
|
||||
RepositoryInformation information;
|
||||
|
||||
@Test
|
||||
@SuppressWarnings({ "rawtypes", "unchecked" })
|
||||
public void findsRepositoryFactories() {
|
||||
|
||||
DefaultListableBeanFactory beanFactory = new DefaultListableBeanFactory() {
|
||||
@Override
|
||||
protected BeanWrapper instantiateBean(String beanName, RootBeanDefinition mbd) {
|
||||
return beanName.equals("repoFactory") ? new BeanWrapperImpl(factory) : super.instantiateBean(beanName, mbd);
|
||||
}
|
||||
};
|
||||
|
||||
beanFactory.registerBeanDefinition("postProcessor", new RootBeanDefinition(PredictingProcessor.class));
|
||||
beanFactory.registerBeanDefinition("repoFactory", new RootBeanDefinition(RepositoryFactoryBeanSupport.class));
|
||||
|
||||
when(information.getRepositoryInterface()).thenReturn((Class) PersonRepository.class);
|
||||
when(information.getDomainType()).thenReturn((Class) Person.class);
|
||||
when(information.getIdType()).thenReturn((Class) Serializable.class);
|
||||
|
||||
EntityInformation<Person, Serializable> entityInformation = new DummyEntityInformation<Person>(Person.class);
|
||||
|
||||
when(factory.getObject()).thenReturn(repository);
|
||||
when(factory.getObjectType()).thenReturn(PersonRepository.class);
|
||||
when(factory.getEntityInformation()).thenReturn(entityInformation);
|
||||
when(factory.getRepositoryInformation()).thenReturn(information);
|
||||
|
||||
GenericApplicationContext context = new GenericApplicationContext(beanFactory);
|
||||
assertThat(context.getBeansOfType(RepositoryFactoryInformation.class).values().size(), is(1));
|
||||
|
||||
DomainClassConverter converter = new DomainClassConverter(new DefaultConversionService());
|
||||
converter.setApplicationContext(context);
|
||||
|
||||
assertThat(converter.matches(TypeDescriptor.valueOf(String.class), TypeDescriptor.valueOf(Person.class)), is(true));
|
||||
}
|
||||
|
||||
static class Person {
|
||||
|
||||
}
|
||||
|
||||
static interface PersonRepository extends CrudRepository<Person, Serializable> {
|
||||
|
||||
}
|
||||
|
||||
static class PredictingProcessor extends InstantiationAwareBeanPostProcessorAdapter {
|
||||
|
||||
@Override
|
||||
public Class<?> predictBeanType(Class<?> beanClass, String beanName) {
|
||||
return RepositoryFactoryBeanSupport.class.equals(beanClass) ? PersonRepository.class : null;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,214 @@
|
||||
/*
|
||||
* Copyright 2008-2012 the original author or authors.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
package org.springframework.data.repository.support;
|
||||
|
||||
import static org.hamcrest.Matchers.*;
|
||||
import static org.junit.Assert.*;
|
||||
import static org.mockito.Matchers.*;
|
||||
import static org.mockito.Mockito.*;
|
||||
|
||||
import java.io.Serializable;
|
||||
import java.util.HashMap;
|
||||
import java.util.Map;
|
||||
|
||||
import org.hamcrest.Description;
|
||||
import org.hamcrest.TypeSafeMatcher;
|
||||
import org.junit.Before;
|
||||
import org.junit.Test;
|
||||
import org.junit.runner.RunWith;
|
||||
import org.mockito.Mock;
|
||||
import org.mockito.runners.MockitoJUnitRunner;
|
||||
import org.springframework.context.ApplicationContext;
|
||||
import org.springframework.core.convert.TypeDescriptor;
|
||||
import org.springframework.core.convert.support.DefaultConversionService;
|
||||
import org.springframework.data.repository.CrudRepository;
|
||||
import org.springframework.data.repository.core.EntityInformation;
|
||||
import org.springframework.data.repository.core.RepositoryInformation;
|
||||
import org.springframework.data.repository.core.support.DummyEntityInformation;
|
||||
import org.springframework.data.repository.core.support.RepositoryFactoryInformation;
|
||||
|
||||
/**
|
||||
* Unit test for {@link DomainClassConverter}.
|
||||
*
|
||||
* @author Oliver Gierke
|
||||
*/
|
||||
@RunWith(MockitoJUnitRunner.class)
|
||||
public class DomainClassConverterUnitTests {
|
||||
|
||||
static final User USER = new User();
|
||||
|
||||
@SuppressWarnings("rawtypes")
|
||||
DomainClassConverter converter;
|
||||
|
||||
TypeDescriptor sourceDescriptor;
|
||||
TypeDescriptor targetDescriptor;
|
||||
|
||||
@SuppressWarnings("rawtypes")
|
||||
Map<String, RepositoryFactoryInformation> providers;
|
||||
|
||||
@Mock
|
||||
ApplicationContext context, parent;
|
||||
@Mock
|
||||
UserRepository repository;
|
||||
@Mock
|
||||
DefaultConversionService service;
|
||||
@Mock
|
||||
RepositoryFactoryInformation<User, Serializable> provider;
|
||||
|
||||
@Before
|
||||
@SuppressWarnings({ "unchecked", "rawtypes" })
|
||||
public void setUp() {
|
||||
|
||||
EntityInformation<User, Serializable> information = new DummyEntityInformation<User>(User.class);
|
||||
RepositoryInformation repositoryInformation = new DummyRepositoryInformation(UserRepository.class);
|
||||
|
||||
converter = new DomainClassConverter(service);
|
||||
providers = new HashMap<String, RepositoryFactoryInformation>();
|
||||
|
||||
sourceDescriptor = TypeDescriptor.valueOf(String.class);
|
||||
targetDescriptor = TypeDescriptor.valueOf(User.class);
|
||||
|
||||
when(provider.getEntityInformation()).thenReturn(information);
|
||||
when(provider.getRepositoryInformation()).thenReturn(repositoryInformation);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void matchFailsIfNoDaoAvailable() throws Exception {
|
||||
|
||||
converter.setApplicationContext(context);
|
||||
assertMatches(false);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void matchesIfConversionInBetweenIsPossible() throws Exception {
|
||||
|
||||
letContextContain(context, provider);
|
||||
converter.setApplicationContext(context);
|
||||
|
||||
when(service.canConvert(String.class, Long.class)).thenReturn(true);
|
||||
|
||||
assertMatches(true);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void matchFailsIfNoIntermediateConversionIsPossible() throws Exception {
|
||||
|
||||
letContextContain(context, provider);
|
||||
converter.setApplicationContext(context);
|
||||
|
||||
when(service.canConvert(String.class, Long.class)).thenReturn(false);
|
||||
|
||||
assertMatches(false);
|
||||
}
|
||||
|
||||
/**
|
||||
* @see DATACMNS-233
|
||||
*/
|
||||
public void returnsNullForNullSource() {
|
||||
assertThat(converter.convert(null, sourceDescriptor, targetDescriptor), is(nullValue()));
|
||||
}
|
||||
|
||||
/**
|
||||
* @see DATACMNS-233
|
||||
*/
|
||||
public void returnsNullForEmptyStringSource() {
|
||||
assertThat(converter.convert("", sourceDescriptor, targetDescriptor), is(nullValue()));
|
||||
}
|
||||
|
||||
private void assertMatches(boolean matchExpected) {
|
||||
|
||||
assertThat(converter.matches(sourceDescriptor, targetDescriptor), is(matchExpected));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void convertsStringToUserCorrectly() throws Exception {
|
||||
|
||||
letContextContain(context, provider);
|
||||
converter.setApplicationContext(context);
|
||||
|
||||
when(service.canConvert(String.class, Long.class)).thenReturn(true);
|
||||
when(service.convert(anyString(), eq(Long.class))).thenReturn(1L);
|
||||
when(repository.findOne(1L)).thenReturn(USER);
|
||||
|
||||
Object user = converter.convert("1", sourceDescriptor, targetDescriptor);
|
||||
assertThat(user, is(instanceOf(User.class)));
|
||||
assertThat(user, is((Object) USER));
|
||||
}
|
||||
|
||||
/**
|
||||
* @see DATACMNS-133
|
||||
*/
|
||||
@Test
|
||||
public void discoversFactoryAndRepoFromParentApplicationContext() {
|
||||
|
||||
letContextContain(parent, provider);
|
||||
when(context.getParentBeanFactory()).thenReturn(parent);
|
||||
when(service.canConvert(String.class, Long.class)).thenReturn(true);
|
||||
|
||||
converter.setApplicationContext(context);
|
||||
assertThat(converter.matches(sourceDescriptor, targetDescriptor), is(true));
|
||||
}
|
||||
|
||||
private void letContextContain(ApplicationContext context, Object bean) {
|
||||
|
||||
configureContextToReturnBeans(context, repository, provider);
|
||||
|
||||
Map<String, Object> beanMap = getBeanAsMap(bean);
|
||||
when(context.getBeansOfType(argThat(is(subtypeOf(bean.getClass()))))).thenReturn(beanMap);
|
||||
}
|
||||
|
||||
private void configureContextToReturnBeans(ApplicationContext context, UserRepository repository,
|
||||
RepositoryFactoryInformation<User, Serializable> provider) {
|
||||
|
||||
Map<String, UserRepository> map = getBeanAsMap(repository);
|
||||
when(context.getBeansOfType(UserRepository.class)).thenReturn(map);
|
||||
|
||||
providers.put("provider", provider);
|
||||
when(context.getBeansOfType(RepositoryFactoryInformation.class)).thenReturn(providers);
|
||||
}
|
||||
|
||||
private <T> Map<String, T> getBeanAsMap(T bean) {
|
||||
|
||||
Map<String, T> beanMap = new HashMap<String, T>();
|
||||
beanMap.put(bean.getClass().getName(), bean);
|
||||
return beanMap;
|
||||
}
|
||||
|
||||
private static <T> TypeSafeMatcher<Class<T>> subtypeOf(final Class<? extends T> type) {
|
||||
|
||||
return new TypeSafeMatcher<Class<T>>() {
|
||||
|
||||
public void describeTo(Description arg0) {
|
||||
|
||||
arg0.appendText("not a subtype of");
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean matchesSafely(Class<T> arg0) {
|
||||
|
||||
return arg0.isAssignableFrom(type);
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
private static class User {
|
||||
|
||||
}
|
||||
|
||||
private static interface UserRepository extends CrudRepository<User, Long> {
|
||||
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,134 @@
|
||||
/*
|
||||
* Copyright 2008-2012 the original author or authors.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
package org.springframework.data.repository.support;
|
||||
|
||||
import static org.hamcrest.Matchers.*;
|
||||
import static org.mockito.Matchers.*;
|
||||
import static org.mockito.Mockito.*;
|
||||
|
||||
import java.io.Serializable;
|
||||
import java.util.HashMap;
|
||||
import java.util.Map;
|
||||
|
||||
import org.hamcrest.Description;
|
||||
import org.hamcrest.TypeSafeMatcher;
|
||||
import org.junit.Before;
|
||||
import org.junit.Test;
|
||||
import org.junit.runner.RunWith;
|
||||
import org.mockito.Mock;
|
||||
import org.mockito.runners.MockitoJUnitRunner;
|
||||
import org.springframework.beans.PropertyEditorRegistry;
|
||||
import org.springframework.context.ApplicationContext;
|
||||
import org.springframework.data.repository.CrudRepository;
|
||||
import org.springframework.data.repository.core.EntityInformation;
|
||||
import org.springframework.data.repository.core.RepositoryInformation;
|
||||
import org.springframework.data.repository.core.support.DummyEntityInformation;
|
||||
import org.springframework.data.repository.core.support.RepositoryFactoryInformation;
|
||||
|
||||
/**
|
||||
* Unit test for {@link DomainClassPropertyEditorRegistrar}.
|
||||
*
|
||||
* @author Oliver Gierke
|
||||
*/
|
||||
@RunWith(MockitoJUnitRunner.class)
|
||||
public class DomainClassPropertyEditorRegistrarUnitTests {
|
||||
|
||||
DomainClassPropertyEditorRegistrar registrar = new DomainClassPropertyEditorRegistrar();
|
||||
@Mock
|
||||
ApplicationContext context;
|
||||
@Mock
|
||||
PropertyEditorRegistry registry;
|
||||
@Mock
|
||||
EntityRepository repository;
|
||||
@Mock
|
||||
RepositoryFactoryInformation<Entity, Serializable> provider;
|
||||
|
||||
DomainClassPropertyEditor<Entity, Serializable> reference;
|
||||
|
||||
@Before
|
||||
public void setup() {
|
||||
|
||||
EntityInformation<Entity, Serializable> entityInformation = new DummyEntityInformation<Entity>(Entity.class);
|
||||
RepositoryInformation repositoryInformation = new DummyRepositoryInformation(EntityRepository.class);
|
||||
|
||||
when(provider.getEntityInformation()).thenReturn(entityInformation);
|
||||
when(provider.getRepositoryInformation()).thenReturn(repositoryInformation);
|
||||
|
||||
Map<String, EntityRepository> map = getBeanAsMap(repository);
|
||||
when(context.getBeansOfType(EntityRepository.class)).thenReturn(map);
|
||||
|
||||
reference = new DomainClassPropertyEditor<Entity, Serializable>(repository, entityInformation, registry);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void addsRepositoryForEntityIfAvailableInAppContext() throws Exception {
|
||||
|
||||
letContextContain(provider);
|
||||
registrar.setApplicationContext(context);
|
||||
registrar.registerCustomEditors(registry);
|
||||
|
||||
verify(registry).registerCustomEditor(eq(Entity.class), eq(reference));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void doesNotAddDaoAtAllIfNoDaosFound() throws Exception {
|
||||
|
||||
letContextContain(provider);
|
||||
registrar.registerCustomEditors(registry);
|
||||
|
||||
verify(registry, never()).registerCustomEditor(eq(Entity.class), eq(reference));
|
||||
}
|
||||
|
||||
private void letContextContain(Object bean) {
|
||||
|
||||
Map<String, Object> beanMap = getBeanAsMap(bean);
|
||||
|
||||
when(context.getBeansOfType(argThat(is(subtypeOf(bean.getClass()))))).thenReturn(beanMap);
|
||||
}
|
||||
|
||||
private <T> Map<String, T> getBeanAsMap(T bean) {
|
||||
|
||||
Map<String, T> beanMap = new HashMap<String, T>();
|
||||
beanMap.put(bean.toString(), bean);
|
||||
return beanMap;
|
||||
}
|
||||
|
||||
@SuppressWarnings("serial")
|
||||
private static class Entity implements Serializable {
|
||||
|
||||
}
|
||||
|
||||
private static interface EntityRepository extends CrudRepository<Entity, Serializable> {
|
||||
|
||||
}
|
||||
|
||||
private static <T> TypeSafeMatcher<Class<T>> subtypeOf(final Class<? extends T> type) {
|
||||
|
||||
return new TypeSafeMatcher<Class<T>>() {
|
||||
|
||||
public void describeTo(Description arg0) {
|
||||
|
||||
arg0.appendText("not a subtype of");
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean matchesSafely(Class<T> arg0) {
|
||||
|
||||
return arg0.isAssignableFrom(type);
|
||||
}
|
||||
};
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,164 @@
|
||||
/*
|
||||
* Copyright 2008-2011 the original author or authors.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
package org.springframework.data.repository.support;
|
||||
|
||||
import static org.hamcrest.CoreMatchers.*;
|
||||
import static org.junit.Assert.*;
|
||||
import static org.mockito.Mockito.*;
|
||||
|
||||
import java.beans.PropertyEditor;
|
||||
|
||||
import org.junit.Before;
|
||||
import org.junit.Test;
|
||||
import org.junit.runner.RunWith;
|
||||
import org.mockito.Mock;
|
||||
import org.mockito.runners.MockitoJUnitRunner;
|
||||
import org.springframework.beans.PropertyEditorRegistry;
|
||||
import org.springframework.data.domain.Persistable;
|
||||
import org.springframework.data.repository.CrudRepository;
|
||||
import org.springframework.data.repository.core.EntityInformation;
|
||||
|
||||
/**
|
||||
* Unit test for {@link DomainClassPropertyEditor}.
|
||||
*
|
||||
* @author Oliver Gierke
|
||||
*/
|
||||
@RunWith(MockitoJUnitRunner.class)
|
||||
public class DomainClassPropertyEditorUnitTests {
|
||||
|
||||
DomainClassPropertyEditor<User, Integer> editor;
|
||||
|
||||
@Mock
|
||||
PropertyEditorRegistry registry;
|
||||
@Mock
|
||||
UserRepository userRepository;
|
||||
@Mock
|
||||
EntityInformation<User, Integer> information;
|
||||
|
||||
@Before
|
||||
public void setUp() {
|
||||
|
||||
when(information.getIdType()).thenReturn(Integer.class);
|
||||
editor = new DomainClassPropertyEditor<User, Integer>(userRepository, information, registry);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void convertsPlainIdTypeCorrectly() throws Exception {
|
||||
|
||||
User user = new User(1);
|
||||
when(information.getId(user)).thenReturn(user.getId());
|
||||
when(userRepository.findOne(1)).thenReturn(user);
|
||||
|
||||
editor.setAsText("1");
|
||||
|
||||
verify(userRepository, times(1)).findOne(1);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void convertsEntityToIdCorrectly() throws Exception {
|
||||
|
||||
User user = new User(1);
|
||||
editor.setValue(user);
|
||||
when(information.getId(user)).thenReturn(user.getId());
|
||||
assertThat(editor.getAsText(), is("1"));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void usesCustomEditorIfConfigured() throws Exception {
|
||||
|
||||
PropertyEditor customEditor = mock(PropertyEditor.class);
|
||||
when(customEditor.getValue()).thenReturn(1);
|
||||
|
||||
when(registry.findCustomEditor(Integer.class, null)).thenReturn(customEditor);
|
||||
|
||||
convertsPlainIdTypeCorrectly();
|
||||
|
||||
verify(customEditor, times(1)).setAsText("1");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void returnsNullIdIfNoEntitySet() throws Exception {
|
||||
|
||||
editor.setValue(null);
|
||||
assertThat(editor.getAsText(), is(nullValue()));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void resetsValueToNullAfterEmptyStringConversion() throws Exception {
|
||||
|
||||
assertValueResetToNullAfterConverting("");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void resetsValueToNullAfterNullStringConversion() throws Exception {
|
||||
|
||||
assertValueResetToNullAfterConverting(null);
|
||||
}
|
||||
|
||||
private void assertValueResetToNullAfterConverting(String source) throws Exception {
|
||||
|
||||
convertsPlainIdTypeCorrectly();
|
||||
assertThat(editor.getValue(), is(notNullValue()));
|
||||
|
||||
editor.setAsText(source);
|
||||
assertThat(editor.getValue(), is(nullValue()));
|
||||
}
|
||||
|
||||
/**
|
||||
* Sample entity.
|
||||
*
|
||||
* @author Oliver Gierke
|
||||
*/
|
||||
@SuppressWarnings("serial")
|
||||
private static class User implements Persistable<Integer> {
|
||||
|
||||
private Integer id;
|
||||
|
||||
public User(Integer id) {
|
||||
|
||||
this.id = id;
|
||||
}
|
||||
|
||||
/*
|
||||
* (non-Javadoc)
|
||||
*
|
||||
* @see org.springframework.data.domain.Persistable#getId()
|
||||
*/
|
||||
public Integer getId() {
|
||||
|
||||
return id;
|
||||
}
|
||||
|
||||
/*
|
||||
* (non-Javadoc)
|
||||
*
|
||||
* @see org.springframework.data.domain.Persistable#isNew()
|
||||
*/
|
||||
public boolean isNew() {
|
||||
|
||||
return getId() != null;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Sample generic DAO interface.
|
||||
*
|
||||
* @author Oliver Gierke
|
||||
*/
|
||||
private static interface UserRepository extends CrudRepository<User, Integer> {
|
||||
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,74 @@
|
||||
/*
|
||||
* Copyright 2012 the original author or authors.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
package org.springframework.data.repository.support;
|
||||
|
||||
import java.io.Serializable;
|
||||
import java.lang.reflect.Method;
|
||||
import java.util.Collections;
|
||||
import java.util.Set;
|
||||
|
||||
import org.springframework.data.repository.core.RepositoryInformation;
|
||||
import org.springframework.data.repository.core.RepositoryMetadata;
|
||||
import org.springframework.data.repository.core.support.DefaultRepositoryMetadata;
|
||||
|
||||
public final class DummyRepositoryInformation implements RepositoryInformation {
|
||||
|
||||
private final RepositoryMetadata metadata;
|
||||
|
||||
public DummyRepositoryInformation(Class<?> repositoryInterface) {
|
||||
this.metadata = new DefaultRepositoryMetadata(repositoryInterface);
|
||||
}
|
||||
|
||||
public Class<? extends Serializable> getIdType() {
|
||||
return metadata.getIdType();
|
||||
}
|
||||
|
||||
public Class<?> getDomainType() {
|
||||
return metadata.getDomainType();
|
||||
}
|
||||
|
||||
public Class<?> getRepositoryInterface() {
|
||||
return metadata.getRepositoryInterface();
|
||||
}
|
||||
|
||||
public Class<?> getReturnedDomainClass(Method method) {
|
||||
return getDomainType();
|
||||
}
|
||||
|
||||
public Class<?> getRepositoryBaseClass() {
|
||||
return getRepositoryInterface();
|
||||
}
|
||||
|
||||
public boolean hasCustomMethod() {
|
||||
return false;
|
||||
}
|
||||
|
||||
public boolean isCustomMethod(Method method) {
|
||||
return false;
|
||||
}
|
||||
|
||||
public boolean isQueryMethod(Method method) {
|
||||
return false;
|
||||
}
|
||||
|
||||
public Set<Method> getQueryMethods() {
|
||||
return Collections.emptySet();
|
||||
}
|
||||
|
||||
public Method getTargetClassMethod(Method method) {
|
||||
return method;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,162 @@
|
||||
/*
|
||||
* Copyright 2012 the original author or authors.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except
|
||||
import org.springframework.data.repository.core.support.DefaultRepositoryMetadata;
|
||||
in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
package org.springframework.data.repository.support;
|
||||
|
||||
import static org.hamcrest.CoreMatchers.*;
|
||||
import static org.junit.Assert.*;
|
||||
import static org.mockito.Mockito.*;
|
||||
|
||||
import java.io.Serializable;
|
||||
import java.util.Collections;
|
||||
import java.util.HashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
import org.junit.Before;
|
||||
import org.junit.Test;
|
||||
import org.junit.runner.RunWith;
|
||||
import org.mockito.Mock;
|
||||
import org.mockito.runners.MockitoJUnitRunner;
|
||||
import org.springframework.context.ApplicationContext;
|
||||
import org.springframework.data.mapping.MappingMetadataTests.SampleMappingContext;
|
||||
import org.springframework.data.mapping.PersistentEntity;
|
||||
import org.springframework.data.repository.CrudRepository;
|
||||
import org.springframework.data.repository.Repository;
|
||||
import org.springframework.data.repository.core.EntityInformation;
|
||||
import org.springframework.data.repository.core.RepositoryInformation;
|
||||
import org.springframework.data.repository.core.RepositoryMetadata;
|
||||
import org.springframework.data.repository.core.support.DefaultRepositoryMetadata;
|
||||
import org.springframework.data.repository.core.support.DummyEntityInformation;
|
||||
import org.springframework.data.repository.core.support.RepositoryFactoryInformation;
|
||||
import org.springframework.data.repository.query.QueryMethod;
|
||||
|
||||
/**
|
||||
* Unit tests for {@link Repositories}.
|
||||
*
|
||||
* @author Oliver Gierke
|
||||
*/
|
||||
@RunWith(MockitoJUnitRunner.class)
|
||||
public class RepositoriesUnitTests {
|
||||
|
||||
@Mock
|
||||
PersonRepository personRepository;
|
||||
@Mock
|
||||
AddressRepository addressRepository;
|
||||
@Mock
|
||||
ApplicationContext context;
|
||||
|
||||
@Before
|
||||
@SuppressWarnings({ "unchecked", "rawtypes" })
|
||||
public void setUp() {
|
||||
|
||||
Map factoryInformations = getBeanAsMap(new SampleRepoFactoryInformation<Address, Long>(AddressRepository.class),
|
||||
new SampleRepoFactoryInformation<Person, Long>(PersonRepository.class));
|
||||
Map<String, PersonRepository> personRepositories = getBeanAsMap(personRepository);
|
||||
Map<String, AddressRepository> addressRepositories = getBeanAsMap(addressRepository);
|
||||
|
||||
when(context.getBeansOfType(RepositoryFactoryInformation.class)).thenReturn(factoryInformations);
|
||||
when(context.getBeansOfType(PersonRepository.class)).thenReturn(personRepositories);
|
||||
when(context.getBeansOfType(AddressRepository.class)).thenReturn(addressRepositories);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void considersCrudRepositoriesOnly() {
|
||||
|
||||
Repositories repositories = new Repositories(context);
|
||||
|
||||
assertThat(repositories.hasRepositoryFor(Person.class), is(true));
|
||||
assertThat(repositories.hasRepositoryFor(Address.class), is(false));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void doesNotFindInformationForNonManagedDomainClass() {
|
||||
Repositories repositories = new Repositories(context);
|
||||
assertThat(repositories.hasRepositoryFor(String.class), is(false));
|
||||
assertThat(repositories.getRepositoryFor(String.class), is(nullValue()));
|
||||
}
|
||||
|
||||
@Test(expected = IllegalArgumentException.class)
|
||||
public void rejectsNullBeanFactory() {
|
||||
new Repositories(null);
|
||||
}
|
||||
|
||||
/**
|
||||
* @see DATACMNS-256
|
||||
*/
|
||||
@Test
|
||||
public void exposesPersistentEntityForDomainTypes() {
|
||||
|
||||
Repositories repositories = new Repositories(context);
|
||||
assertThat(repositories.getPersistentEntity(Person.class), is(notNullValue()));
|
||||
assertThat(repositories.getPersistentEntity(Address.class), is(nullValue()));
|
||||
}
|
||||
|
||||
class Person {
|
||||
|
||||
}
|
||||
|
||||
class Address {
|
||||
|
||||
}
|
||||
|
||||
interface PersonRepository extends CrudRepository<Person, Long> {
|
||||
|
||||
}
|
||||
|
||||
interface AddressRepository extends Repository<Address, Long> {
|
||||
|
||||
}
|
||||
|
||||
static class SampleRepoFactoryInformation<T, S extends Serializable> implements RepositoryFactoryInformation<T, S> {
|
||||
|
||||
private final RepositoryMetadata repositoryMetadata;
|
||||
private final SampleMappingContext mappingContext;
|
||||
|
||||
public SampleRepoFactoryInformation(Class<?> repositoryInterface) {
|
||||
this.repositoryMetadata = new DefaultRepositoryMetadata(repositoryInterface);
|
||||
this.mappingContext = new SampleMappingContext();
|
||||
}
|
||||
|
||||
@SuppressWarnings({ "unchecked", "rawtypes" })
|
||||
public EntityInformation<T, S> getEntityInformation() {
|
||||
return new DummyEntityInformation(repositoryMetadata.getDomainType());
|
||||
}
|
||||
|
||||
public RepositoryInformation getRepositoryInformation() {
|
||||
return new DummyRepositoryInformation(repositoryMetadata.getRepositoryInterface());
|
||||
}
|
||||
|
||||
public PersistentEntity<?, ?> getPersistentEntity() {
|
||||
return mappingContext.getPersistentEntity(repositoryMetadata.getDomainType());
|
||||
}
|
||||
|
||||
public List<QueryMethod> getQueryMethods() {
|
||||
return Collections.emptyList();
|
||||
}
|
||||
}
|
||||
|
||||
private static <T> Map<String, T> getBeanAsMap(T... beans) {
|
||||
|
||||
Map<String, T> beanMap = new HashMap<String, T>();
|
||||
|
||||
for (T bean : beans) {
|
||||
beanMap.put(bean.toString(), bean);
|
||||
}
|
||||
return beanMap;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,78 @@
|
||||
/*
|
||||
* Copyright 2008-2010 the original author or authors.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
package org.springframework.data.repository.util;
|
||||
|
||||
import static org.junit.Assert.*;
|
||||
import static org.springframework.data.repository.util.ClassUtils.*;
|
||||
|
||||
import java.io.Serializable;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
import org.junit.Test;
|
||||
import org.springframework.data.domain.Page;
|
||||
import org.springframework.data.domain.Pageable;
|
||||
import org.springframework.data.repository.Repository;
|
||||
|
||||
/**
|
||||
* Unit test for {@link ClassUtils}.
|
||||
*
|
||||
* @author Oliver Gierke
|
||||
*/
|
||||
public class ClassUtilsUnitTests {
|
||||
|
||||
@Test(expected = IllegalStateException.class)
|
||||
public void rejectsInvalidReturnType() throws Exception {
|
||||
|
||||
assertReturnTypeAssignable(SomeDao.class.getMethod("findByFirstname", Pageable.class, String.class), User.class);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void determinesValidFieldsCorrectly() {
|
||||
|
||||
assertTrue(hasProperty(User.class, "firstname"));
|
||||
assertTrue(hasProperty(User.class, "Firstname"));
|
||||
assertFalse(hasProperty(User.class, "address"));
|
||||
}
|
||||
|
||||
@SuppressWarnings("unused")
|
||||
private class User {
|
||||
|
||||
private String firstname;
|
||||
|
||||
public String getAddress() {
|
||||
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
static interface UserRepository extends Repository<User, Integer> {
|
||||
|
||||
}
|
||||
|
||||
interface SomeDao extends Serializable, UserRepository {
|
||||
|
||||
Page<User> findByFirstname(Pageable pageable, String firstname);
|
||||
|
||||
GenericType<User> someMethod();
|
||||
|
||||
List<Map<String, Object>> anotherMethod();
|
||||
}
|
||||
|
||||
class GenericType<T> {
|
||||
|
||||
}
|
||||
}
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user