BAEL-3335 example of reading request multiple times. removed spring boot and using spring-webmvc

This commit is contained in:
sumit-bhawsar
2019-10-20 04:01:29 +01:00
parent db85c8f275
commit 2e97ec17f4
20450 changed files with 1641014 additions and 0 deletions
@@ -0,0 +1,22 @@
package org.baeldung.autowire.sample;
import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.context.support.AnnotationConfigContextLoader;
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = AppConfig.class, loader = AnnotationConfigContextLoader.class)
public class FooServiceIntegrationTest {
@Autowired
FooService fooService;
@Test
public void whenFooFormatterType_thenReturnFoo() {
Assert.assertEquals("foo", fooService.doStuff());
}
}
@@ -0,0 +1,21 @@
package org.baeldung.bean.injection;
import org.baeldung.bean.config.ConstructorBasedShipConfig;
import org.junit.Assert;
import org.junit.Test;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
public class ConstructorBasedBeanInjectionWithJavaConfigIntegrationTest {
private static final String HELM_NAME = "HelmBrand";
@Test
public void givenJavaConfigFile_whenUsingConstructorBasedBeanInjection_thenCorrectHelmName() {
AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext();
ctx.register(ConstructorBasedShipConfig.class);
ctx.refresh();
Ship ship = ctx.getBean(Ship.class);
Assert.assertEquals(HELM_NAME, ship.getHelm().getBrandOfHelm());
}
}
@@ -0,0 +1,19 @@
package org.baeldung.bean.injection;
import org.junit.Assert;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class ConstructorBasedBeanInjectionWithXMLConfigIntegrationTest {
private static final String HELM_NAME = "HelmBrand";
@Test
public void givenXMLConfigFile_whenUsingConstructorBasedBeanInjection_thenCorrectHelmName() {
final ApplicationContext applicationContext = new ClassPathXmlApplicationContext("beanInjection-constructor.xml");
final Ship shipConstructorBean = (Ship) applicationContext.getBean("ship");
Assert.assertEquals(HELM_NAME, shipConstructorBean.getHelm().getBrandOfHelm());
}
}
@@ -0,0 +1,23 @@
package org.baeldung.bean.injection;
import org.baeldung.bean.config.SetterBasedShipConfig;
import org.junit.Assert;
import org.junit.Test;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
public class SetterBasedBeanInjectionWithJavaConfigIntegrationTest {
private static final String HELM_NAME = "HelmBrand";
@Test
public void givenJavaConfigFile_whenUsingSetterBasedBeanInjection_thenCorrectHelmName() {
AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext();
ctx.register(SetterBasedShipConfig.class);
ctx.refresh();
Ship ship = ctx.getBean(Ship.class);
Assert.assertEquals(HELM_NAME, ship.getHelm().getBrandOfHelm());
}
}
@@ -0,0 +1,19 @@
package org.baeldung.bean.injection;
import org.junit.Assert;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class SetterBasedBeanInjectionWithXMLConfigIntegrationTest {
private static final String HELM_NAME = "HelmBrand";
@Test
public void givenXMLConfigFile_whenUsingSetterBasedBeanInjection_thenCorrectHelmName() {
final ApplicationContext applicationContext = new ClassPathXmlApplicationContext("beanInjection-setter.xml");
final Ship shipSetterBean = (Ship) applicationContext.getBean("ship");
Assert.assertEquals(HELM_NAME, shipSetterBean.getHelm().getBrandOfHelm());
}
}
@@ -0,0 +1,62 @@
package org.baeldung.cachedrequest;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import org.junit.After;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.junit.MockitoJUnitRunner;
import org.springframework.mock.web.MockHttpServletRequest;
import org.springframework.util.StreamUtils;
import junit.framework.TestCase;
@RunWith(MockitoJUnitRunner.class)
public class CachedBodyHttpServletRequestUnitTest extends TestCase {
private CachedBodyServletInputStream servletInputStream;
@After
public void cleanUp() throws IOException {
if (null != servletInputStream) {
servletInputStream.close();
}
}
@Test
public void testGivenHttpServletRequestWithBody_whenCalledGetInputStream_ThenGetsServletInputStreamWithSameBody() throws IOException {
// Given
byte[] cachedBody = "{\"firstName\" :\"abc\",\"lastName\" : \"xyz\",\"age\" : 30\"}".getBytes();
MockHttpServletRequest mockeddHttpServletRequest = new MockHttpServletRequest();
mockeddHttpServletRequest.setContent(cachedBody);
CachedBodyHttpServletRequest request = new CachedBodyHttpServletRequest(mockeddHttpServletRequest);
// when
InputStream inputStream = request.getInputStream();
// then
assertEquals(new String(cachedBody), new String(StreamUtils.copyToByteArray(inputStream)));
}
@Test
public void testGivenHttpServletRequestWithBody_whenCalledGetReader_ThenGetBufferedReaderWithSameBody() throws IOException {
// Given
byte[] cachedBody = "{\"firstName\" :\"abc\",\"lastName\" : \"xyz\",\"age\" : 30\"}".getBytes();
MockHttpServletRequest mockeddHttpServletRequest = new MockHttpServletRequest();
mockeddHttpServletRequest.setContent(cachedBody);
CachedBodyHttpServletRequest request = new CachedBodyHttpServletRequest(mockeddHttpServletRequest);
// when
BufferedReader bufferedReader = request.getReader();
// then
String line = "";
StringBuilder builder = new StringBuilder();
while ((line = bufferedReader.readLine()) != null) {
builder.append(line);
}
assertEquals(new String(cachedBody), builder.toString());
}
}
@@ -0,0 +1,98 @@
package org.baeldung.cachedrequest;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import javax.servlet.ReadListener;
import org.junit.After;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mockito;
import org.mockito.junit.MockitoJUnitRunner;
import org.springframework.util.StreamUtils;
import junit.framework.TestCase;
@RunWith(MockitoJUnitRunner.class)
public class CachedBodyServletInputStreamUnitTest extends TestCase {
private CachedBodyServletInputStream servletInputStream;
@After
public void cleanUp() throws IOException {
if (null != servletInputStream) {
servletInputStream.close();
}
}
@Test
public void testGivenServletInputStreamCreated_whenCalledisFinished_Thenfalse() {
// Given
byte[] cachedBody = "{\"firstName\" :\"abc\",\"lastName\" : \"xyz\",\"age\" : 30\"}".getBytes();
servletInputStream = new CachedBodyServletInputStream(cachedBody);
// when
boolean finished = servletInputStream.isFinished();
// then
assertFalse(finished);
}
@Test
public void testGivenServletInputStreamCreatedAndBodyRead_whenCalledisFinished_ThenTrue() throws IOException {
// Given
byte[] cachedBody = "{\"firstName\" :\"abc\",\"lastName\" : \"xyz\",\"age\" : 30\"}".getBytes();
servletInputStream = new CachedBodyServletInputStream(cachedBody);
StreamUtils.copyToByteArray(servletInputStream);
// when
boolean finished = servletInputStream.isFinished();
// then
assertTrue(finished);
}
@Test
public void testGivenServletInputStreamCreatedAndBodyRead_whenCalledIsReady_ThenTrue() throws IOException {
// Given
byte[] cachedBody = "{\"firstName\" :\"abc\",\"lastName\" : \"xyz\",\"age\" : 30\"}".getBytes();
servletInputStream = new CachedBodyServletInputStream(cachedBody);
// when
boolean ready = servletInputStream.isReady();
// then
assertTrue(ready);
}
@Test
public void testGivenServletInputStreamCreated_whenCalledIsRead_ThenReturnsBody() throws IOException {
// Given
byte[] cachedBody = "{\"firstName\" :\"abc\",\"lastName\" : \"xyz\",\"age\" : 30\"}".getBytes();
servletInputStream = new CachedBodyServletInputStream(cachedBody);
// when
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
int len = 0;
byte[] buffer = new byte[1024];
while ((len = servletInputStream.read(buffer)) != -1) {
byteArrayOutputStream.write(buffer, 0, len);
}
// then
assertEquals(new String(cachedBody), new String(byteArrayOutputStream.toByteArray()));
}
@Test(expected = UnsupportedOperationException.class)
public void testGivenServletInputStreamCreated_whenCalledIsRead_ThenThrowsException() throws IOException {
// Given
byte[] cachedBody = "{\"firstName\" :\"abc\",\"lastName\" : \"xyz\",\"age\" : 30\"}".getBytes();
servletInputStream = new CachedBodyServletInputStream(cachedBody);
// when
servletInputStream.setReadListener(Mockito.mock(ReadListener.class));
}
}
@@ -0,0 +1,39 @@
package org.baeldung.cachedrequest;
import java.io.IOException;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.InjectMocks;
import org.mockito.Mockito;
import org.mockito.junit.MockitoJUnitRunner;
import org.springframework.mock.web.MockHttpServletRequest;
import org.springframework.mock.web.MockHttpServletResponse;
import junit.framework.TestCase;
@RunWith(MockitoJUnitRunner.class)
public class ContentCachingFilterUnitTest extends TestCase {
@InjectMocks
private ContentCachingFilter filterToTest;
@Test
public void testGivenHttpRequest_WhenDoFilter_thenCreatesRequestWrapperObject() throws IOException, ServletException {
// Given
MockHttpServletRequest mockedRequest = new MockHttpServletRequest();
MockHttpServletResponse mockedResponse = new MockHttpServletResponse();
FilterChain mockedFilterChain = Mockito.mock(FilterChain.class);
// when
filterToTest.doFilter(mockedRequest, mockedResponse, mockedFilterChain);
// then
Mockito.verify(mockedFilterChain, Mockito.times(1))
.doFilter(Mockito.any(CachedBodyHttpServletRequest.class), Mockito.any(MockHttpServletResponse.class));
}
}
@@ -0,0 +1,46 @@
package org.baeldung.cachedrequest;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
import java.io.IOException;
import javax.print.attribute.PrintRequestAttribute;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.http.MediaType;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.ResultActions;
import com.fasterxml.jackson.databind.ObjectMapper;
@RunWith(SpringRunner.class)
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT, classes = { HttpRequestDemoConfig.class, ContentCachingFilter.class, PrintRequestAttribute.class })
@AutoConfigureMockMvc
public class PersonControllerIntegrationTest {
@Autowired
private MockMvc mockMvc;
ObjectMapper objectMapper = new ObjectMapper();
@Test
public void whenValidInput_thenCreateBook() throws IOException, Exception {
// assign - given
Person book = new Person("sumit", "abc", 100);
// act - when
ResultActions result = mockMvc.perform(post("/person").accept(MediaType.APPLICATION_JSON)
.contentType(MediaType.APPLICATION_JSON)
.content(objectMapper.writeValueAsString(book)));
// assert - then
result.andExpect(status().isNoContent());
}
}
@@ -0,0 +1,40 @@
package org.baeldung.cachedrequest;
import java.io.IOException;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.InjectMocks;
import org.mockito.Mockito;
import org.mockito.junit.MockitoJUnitRunner;
import org.springframework.mock.web.MockHttpServletRequest;
import org.springframework.mock.web.MockHttpServletResponse;
import junit.framework.TestCase;
@RunWith(MockitoJUnitRunner.class)
public class PrintRequestContentFilterUnitTest extends TestCase {
@InjectMocks
private PrintRequestContentFilter filterToTest;
@Test
public void testGivenHttpRequest_WhenDoFilter_thenReadsBody() throws IOException, ServletException {
// Given
MockHttpServletRequest mockedRequest = new MockHttpServletRequest();
MockHttpServletResponse mockedResponse = new MockHttpServletResponse();
FilterChain mockedFilterChain = Mockito.mock(FilterChain.class);
CachedBodyHttpServletRequest cachedBodyHttpServletRequest = new CachedBodyHttpServletRequest(mockedRequest);
// when
filterToTest.doFilter(cachedBodyHttpServletRequest, mockedResponse, mockedFilterChain);
// then
Mockito.verify(mockedFilterChain, Mockito.times(1))
.doFilter(cachedBodyHttpServletRequest, mockedResponse);
}
}
@@ -0,0 +1,40 @@
package org.baeldung.customannotation;
import java.io.Serializable;
public class Account implements Serializable {
private static final long serialVersionUID = 7857541629844398625L;
private Long id;
private String email;
private Person person;
public Account() {
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public Person getPerson() {
return person;
}
public void setPerson(Person person) {
this.person = person;
}
}
@@ -0,0 +1,18 @@
package org.baeldung.customannotation;
import org.springframework.stereotype.Repository;
@Repository
public class BeanWithGenericDAO {
@DataAccess(entity = Person.class)
private GenericDAO<Person> personGenericDAO;
public BeanWithGenericDAO() {
}
public GenericDAO<Person> getPersonGenericDAO() {
return personGenericDAO;
}
}
@@ -0,0 +1,57 @@
package org.baeldung.customannotation;
import static org.hamcrest.CoreMatchers.equalTo;
import static org.hamcrest.CoreMatchers.is;
import static org.hamcrest.CoreMatchers.not;
import static org.hamcrest.CoreMatchers.notNullValue;
import static org.hamcrest.CoreMatchers.sameInstance;
import static org.junit.Assert.assertThat;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = { CustomAnnotationConfiguration.class })
public class DataAccessAnnotationIntegrationTest {
@DataAccess(entity = Person.class)
private GenericDAO<Person> personGenericDAO;
@DataAccess(entity = Account.class)
private GenericDAO<Account> accountGenericDAO;
@DataAccess(entity = Person.class)
private GenericDAO<Person> anotherPersonGenericDAO;
@Test
public void whenGenericDAOInitialized_thenNotNull() {
assertThat(personGenericDAO, is(notNullValue()));
assertThat(accountGenericDAO, is(notNullValue()));
}
@Test
public void whenGenericDAOInjected_thenItIsSingleton() {
assertThat(personGenericDAO, not(sameInstance(accountGenericDAO)));
assertThat(personGenericDAO, not(equalTo(accountGenericDAO)));
assertThat(personGenericDAO, sameInstance(anotherPersonGenericDAO));
}
@Test
public void whenFindAll_thenMessagesIsCorrect() {
personGenericDAO.findAll();
assertThat(personGenericDAO.getMessage(), is("Would create findAll query from Person"));
accountGenericDAO.findAll();
assertThat(accountGenericDAO.getMessage(), is("Would create findAll query from Account"));
}
@Test
public void whenPersist_thenMakeSureThatMessagesIsCorrect() {
personGenericDAO.persist(new Person());
assertThat(personGenericDAO.getMessage(), is("Would create persist query from Person"));
accountGenericDAO.persist(new Account());
assertThat(accountGenericDAO.getMessage(), is("Would create persist query from Account"));
}
}
@@ -0,0 +1,51 @@
package org.baeldung.customannotation;
import static org.hamcrest.CoreMatchers.is;
import static org.hamcrest.CoreMatchers.notNullValue;
import static org.junit.Assert.assertThat;
import java.lang.reflect.Type;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ExpectedException;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.config.ConfigurableListableBeanFactory;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = { CustomAnnotationConfiguration.class })
public class DataAccessFieldCallbackIntegrationTest {
@Autowired
private ConfigurableListableBeanFactory configurableListableBeanFactory;
@Autowired
private BeanWithGenericDAO beanWithGenericDAO;
@Rule
public ExpectedException ex = ExpectedException.none();
@Test
public void whenObjectCreated_thenObjectCreationIsSuccessful() {
final DataAccessFieldCallback dataAccessFieldCallback = new DataAccessFieldCallback(configurableListableBeanFactory, beanWithGenericDAO);
assertThat(dataAccessFieldCallback, is(notNullValue()));
}
@Test
public void whenMethodGenericTypeIsValidCalled_thenReturnCorrectValue() throws NoSuchFieldException, SecurityException {
final DataAccessFieldCallback callback = new DataAccessFieldCallback(configurableListableBeanFactory, beanWithGenericDAO);
final Type fieldType = BeanWithGenericDAO.class.getDeclaredField("personGenericDAO").getGenericType();
final boolean result = callback.genericTypeIsValid(Person.class, fieldType);
assertThat(result, is(true));
}
@Test
public void whenMethodGetBeanInstanceCalled_thenReturnCorrectInstance() {
final DataAccessFieldCallback callback = new DataAccessFieldCallback(configurableListableBeanFactory, beanWithGenericDAO);
final Object result = callback.getBeanInstance("personGenericDAO", GenericDAO.class, Person.class);
assertThat((result instanceof GenericDAO), is(true));
}
}
@@ -0,0 +1,31 @@
package org.baeldung.customannotation;
import java.io.Serializable;
public class Person implements Serializable {
private static final long serialVersionUID = 9005331414216374586L;
private Long id;
private String name;
public Person() {
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
@@ -0,0 +1,72 @@
package org.baeldung.customscope;
import static org.hamcrest.CoreMatchers.equalTo;
import static org.hamcrest.CoreMatchers.not;
import static org.junit.Assert.assertThat;
import static org.junit.Assert.assertTrue;
import java.util.Map;
import org.junit.Test;
import org.springframework.beans.factory.config.BeanDefinition;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
public class TenantScopeIntegrationTest {
@Test
public final void whenRegisterScopeAndBeans_thenContextContainsFooAndBar() {
AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext();
try {
ctx.register(TenantScopeConfig.class);
ctx.register(TenantBeansConfig.class);
ctx.refresh();
TenantBean foo = (TenantBean) ctx.getBean("foo", TenantBean.class);
foo.sayHello();
TenantBean bar = (TenantBean) ctx.getBean("bar", TenantBean.class);
bar.sayHello();
Map<String, TenantBean> foos = ctx.getBeansOfType(TenantBean.class);
assertThat(foo, not(equalTo(bar)));
assertThat(foos.size(), equalTo(2));
assertTrue(foos.containsValue(foo));
assertTrue(foos.containsValue(bar));
BeanDefinition fooDefinition = ctx.getBeanDefinition("foo");
BeanDefinition barDefinition = ctx.getBeanDefinition("bar");
assertThat(fooDefinition.getScope(), equalTo("tenant"));
assertThat(barDefinition.getScope(), equalTo("tenant"));
} finally {
ctx.close();
}
}
@Test
public final void whenComponentScan_thenContextContainsFooAndBar() {
AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext();
try {
ctx.scan("org.baeldung.customscope");
ctx.refresh();
TenantBean foo = (TenantBean) ctx.getBean("foo", TenantBean.class);
foo.sayHello();
TenantBean bar = (TenantBean) ctx.getBean("bar", TenantBean.class);
bar.sayHello();
Map<String, TenantBean> foos = ctx.getBeansOfType(TenantBean.class);
assertThat(foo, not(equalTo(bar)));
assertThat(foos.size(), equalTo(2));
assertTrue(foos.containsValue(foo));
assertTrue(foos.containsValue(bar));
BeanDefinition fooDefinition = ctx.getBeanDefinition("foo");
BeanDefinition barDefinition = ctx.getBeanDefinition("bar");
assertThat(fooDefinition.getScope(), equalTo("tenant"));
assertThat(barDefinition.getScope(), equalTo("tenant"));
} finally {
ctx.close();
}
}
}
@@ -0,0 +1,37 @@
package org.baeldung.order;
import static org.hamcrest.CoreMatchers.equalTo;
import static org.hamcrest.CoreMatchers.is;
import static org.junit.Assert.assertThat;
import java.util.List;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.context.support.AnnotationConfigContextLoader;
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(loader = AnnotationConfigContextLoader.class)
public class RatingRetrieverUnitTest {
@Configuration
@ComponentScan(basePackages = {"org.baeldung.order"})
static class ContextConfiguration {}
@Autowired
private List<Rating> ratings;
@Test
public void givenOrderOnComponents_whenInjected_thenAutowireByOrderValue() {
assertThat(ratings.get(0).getRating(), is(equalTo(1)));
assertThat(ratings.get(1).getRating(), is(equalTo(2)));
assertThat(ratings.get(2).getRating(), is(equalTo(3)));
}
}
@@ -0,0 +1,23 @@
package org.baeldung.profiles;
import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ActiveProfiles;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.context.support.AnnotationConfigContextLoader;
@RunWith(SpringJUnit4ClassRunner.class)
@ActiveProfiles("dev")
@ContextConfiguration(classes = { SpringProfilesConfig.class }, loader = AnnotationConfigContextLoader.class)
public class DevProfileWithAnnotationIntegrationTest {
@Autowired
DatasourceConfig datasourceConfig;
@Test
public void testSpringProfiles() {
Assert.assertTrue(datasourceConfig instanceof DevDatasourceConfig);
}
}
@@ -0,0 +1,32 @@
package org.baeldung.profiles;
import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.env.Environment;
import org.springframework.test.context.ActiveProfiles;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.context.support.AnnotationConfigContextLoader;
@RunWith(SpringJUnit4ClassRunner.class)
@ActiveProfiles("production")
@ContextConfiguration(classes = { SpringProfilesConfig.class }, loader = AnnotationConfigContextLoader.class)
public class ProductionProfileWithAnnotationIntegrationTest {
@Autowired
DatasourceConfig datasourceConfig;
@Autowired
Environment environment;
@Test
public void testSpringProfiles() {
for (final String profileName : environment.getActiveProfiles()) {
System.out.println("Currently active profile - " + profileName);
}
Assert.assertEquals("production", environment.getActiveProfiles()[0]);
Assert.assertTrue(datasourceConfig instanceof ProductionDatasourceConfig);
}
}
@@ -0,0 +1,22 @@
package org.baeldung.profiles;
import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.context.support.AnnotationConfigContextLoader;
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = { SpringProfilesConfig.class }, loader = AnnotationConfigContextLoader.class)
public class SpringProfilesWithMavenPropertiesIntegrationTest {
@Autowired
DatasourceConfig datasourceConfig;
@Test
public void testSpringProfiles() {
Assert.assertTrue(datasourceConfig instanceof DevDatasourceConfig);
}
}
@@ -0,0 +1,33 @@
package org.baeldung.profiles;
import org.junit.Assert;
import org.junit.Test;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.core.env.ConfigurableEnvironment;
public class SpringProfilesWithXMLIntegrationTest {
private ClassPathXmlApplicationContext classPathXmlApplicationContext;
@Test
public void testSpringProfilesForDevEnvironment() {
classPathXmlApplicationContext = new ClassPathXmlApplicationContext("classpath:springProfiles-config.xml");
final ConfigurableEnvironment configurableEnvironment = classPathXmlApplicationContext.getEnvironment();
configurableEnvironment.setActiveProfiles("dev");
classPathXmlApplicationContext.refresh();
final DatasourceConfig datasourceConfig = classPathXmlApplicationContext.getBean("devDatasourceConfig", DatasourceConfig.class);
Assert.assertTrue(datasourceConfig instanceof DevDatasourceConfig);
}
@Test
public void testSpringProfilesForProdEnvironment() {
classPathXmlApplicationContext = new ClassPathXmlApplicationContext("classpath:springProfiles-config.xml");
final ConfigurableEnvironment configurableEnvironment = classPathXmlApplicationContext.getEnvironment();
configurableEnvironment.setActiveProfiles("production");
classPathXmlApplicationContext.refresh();
final DatasourceConfig datasourceConfig = classPathXmlApplicationContext.getBean("productionDatasourceConfig", DatasourceConfig.class);
Assert.assertTrue(datasourceConfig instanceof ProductionDatasourceConfig);
}
}
@@ -0,0 +1,43 @@
package org.baeldung.scopes;
import org.junit.Assert;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.AbstractApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class ScopesIntegrationTest {
private static final String NAME = "John Smith";
private static final String NAME_OTHER = "Anna Jones";
@Test
public void givenSingletonScope_whenSetName_thenEqualNames() {
final ApplicationContext applicationContext = new ClassPathXmlApplicationContext("scopes.xml");
final Person personSingletonA = (Person) applicationContext.getBean("personSingleton");
final Person personSingletonB = (Person) applicationContext.getBean("personSingleton");
personSingletonA.setName(NAME);
Assert.assertEquals(NAME, personSingletonB.getName());
((AbstractApplicationContext) applicationContext).close();
}
@Test
public void givenPrototypeScope_whenSetNames_thenDifferentNames() {
final ApplicationContext applicationContext = new ClassPathXmlApplicationContext("scopes.xml");
final Person personPrototypeA = (Person) applicationContext.getBean("personPrototype");
final Person personPrototypeB = (Person) applicationContext.getBean("personPrototype");
personPrototypeA.setName(NAME);
personPrototypeB.setName(NAME_OTHER);
Assert.assertEquals(NAME, personPrototypeA.getName());
Assert.assertEquals(NAME_OTHER, personPrototypeB.getName());
((AbstractApplicationContext) applicationContext).close();
}
}
@@ -0,0 +1,23 @@
package org.baeldung.springevents.asynchronous;
import org.baeldung.springevents.synchronous.CustomSpringEventPublisher;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.context.support.AnnotationConfigContextLoader;
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = { AsynchronousSpringEventsConfig.class }, loader = AnnotationConfigContextLoader.class)
public class AsynchronousCustomSpringEventsIntegrationTest {
@Autowired
private CustomSpringEventPublisher publisher;
@Test
public void testCustomSpringEvents() throws InterruptedException {
publisher.publishEvent("Hello world!!");
System.out.println("Done publishing asynchronous custom event. ");
}
}
@@ -0,0 +1,25 @@
package org.baeldung.springevents.synchronous;
import org.baeldung.springevents.synchronous.SynchronousSpringEventsConfig;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.context.support.AnnotationConfigContextLoader;
import static org.springframework.util.Assert.isTrue;
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = { SynchronousSpringEventsConfig.class }, loader = AnnotationConfigContextLoader.class)
public class ContextRefreshedListenerIntegrationTest {
@Autowired
private ContextRefreshedListener listener;
@Test
public void testContextRefreshedListener() {
System.out.println("Test context re-freshed listener.");
isTrue(listener.isHitContextRefreshedHandler(), "Refresh should be called once");
}
}
@@ -0,0 +1,28 @@
package org.baeldung.springevents.synchronous;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.context.support.AnnotationConfigContextLoader;
import static org.springframework.util.Assert.isTrue;
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = { SynchronousSpringEventsConfig.class }, loader = AnnotationConfigContextLoader.class)
public class GenericAppEventListenerIntegrationTest {
@Autowired
private CustomSpringEventPublisher publisher;
@Autowired
private GenericSpringEventListener listener;
@Test
public void testGenericSpringEvent() {
isTrue(!listener.isHitEventHandler(), "The initial value should be false");
publisher.publishGenericAppEvent("Hello world!!!");
isTrue(listener.isHitEventHandler(), "Now the value should be changed to true");
}
}
@@ -0,0 +1,49 @@
package org.baeldung.springevents.synchronous;
import org.junit.Ignore;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.context.support.AnnotationConfigContextLoader;
import static org.springframework.util.Assert.isTrue;
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = { SynchronousSpringEventsConfig.class }, loader = AnnotationConfigContextLoader.class)
public class SynchronousCustomSpringEventsIntegrationTest {
@Autowired
private CustomSpringEventPublisher publisher;
@Autowired
private AnnotationDrivenEventListener listener;
@Test
public void testCustomSpringEvents() {
isTrue(!listener.isHitCustomEventHandler(), "The value should be false");
publisher.publishEvent("Hello world!!");
System.out.println("Done publishing synchronous custom event. ");
isTrue(listener.isHitCustomEventHandler(), "Now the value should be changed to true");
}
@Test
public void testGenericSpringEvent() {
isTrue(!listener.isHitSuccessfulEventHandler(), "The initial value should be false");
publisher.publishGenericEvent("Hello world!!!", true);
isTrue(listener.isHitSuccessfulEventHandler(), "Now the value should be changed to true");
}
@Test
public void testGenericSpringEventNotProcessed() {
isTrue(!listener.isHitSuccessfulEventHandler(), "The initial value should be false");
publisher.publishGenericEvent("Hello world!!!", false);
isTrue(!listener.isHitSuccessfulEventHandler(), "The value should still be false");
}
@Ignore("fix me")
@Test
public void testContextStartedEvent() {
isTrue(listener.isHitContextStartedHandler(), "Start should be called once");
}
}
@@ -0,0 +1,44 @@
package org.baeldung.startup;
import org.assertj.core.api.Assertions;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.BeanCreationException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.context.support.AnnotationConfigContextLoader;
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = { SpringStartupConfig.class }, loader = AnnotationConfigContextLoader.class)
public class SpringStartupIntegrationTest {
@Autowired
private ApplicationContext ctx;
@Test(expected = BeanCreationException.class)
public void whenInstantiating_shouldThrowBCE() throws Exception {
ctx.getBean(InvalidInitExampleBean.class);
}
@Test
public void whenPostConstruct_shouldLogEnv() throws Exception {
ctx.getBean(PostConstructExampleBean.class);
}
@Test
public void whenConstructorInjection_shouldLogEnv() throws Exception {
ctx.getBean(LogicInConstructorExampleBean.class);
}
@Test
public void whenInitializingBean_shouldLogEnv() throws Exception {
ctx.getBean(InitializingBeanExampleBean.class);
}
@Test
public void whenApplicationListener_shouldRunOnce() throws Exception {
Assertions.assertThat(StartupApplicationListenerExample.counter).isEqualTo(1);
}
}
@@ -0,0 +1,26 @@
package org.baeldung.startup;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration("classpath:startupConfig.xml")
public class SpringStartupXMLConfigIntegrationTest {
@Autowired
private ApplicationContext ctx;
@Test
public void whenPostConstruct_shouldLogEnv() throws Exception {
ctx.getBean(InitMethodExampleBean.class);
}
@Test
public void whenAllStrategies_shouldLogOrder() throws Exception {
ctx.getBean(AllStrategiesExampleBean.class);
}
}
@@ -0,0 +1,13 @@
*.class
#folders#
/target
/neoDb*
/data
/src/main/webapp/WEB-INF/classes
*/META-INF/*
# Packaged files #
*.jar
*.war
*.ear