diff --git a/pom.xml b/pom.xml index ea76ab2b064..559b76a743a 100644 --- a/pom.xml +++ b/pom.xml @@ -251,6 +251,18 @@ 9.1-901-1.jdbc4 test + + org.assertj + assertj-core + 1.7.1 + test + + + eu.codearte.catch-exception + catch-exception + 1.4.4 + test + diff --git a/src/test/java/org/apache/ibatis/autoconstructor/AutoConstructorTest.java b/src/test/java/org/apache/ibatis/autoconstructor/AutoConstructorTest.java index 0a6e74f791c..c41dee8262b 100644 --- a/src/test/java/org/apache/ibatis/autoconstructor/AutoConstructorTest.java +++ b/src/test/java/org/apache/ibatis/autoconstructor/AutoConstructorTest.java @@ -21,7 +21,7 @@ import org.apache.ibatis.session.SqlSession; import org.apache.ibatis.session.SqlSessionFactory; import org.apache.ibatis.session.SqlSessionFactoryBuilder; -import org.hamcrest.CoreMatchers; +import org.assertj.core.api.Assertions; import org.junit.Assert; import org.junit.BeforeClass; import org.junit.Test; @@ -109,6 +109,6 @@ public void badSubject() { private void verifySubjects(final List subjects) { Assert.assertNotNull(subjects); - Assert.assertThat(subjects.size(), CoreMatchers.equalTo(3)); + Assertions.assertThat(subjects.size()).isEqualTo(3); } } diff --git a/src/test/java/org/apache/ibatis/binding/FlushTest.java b/src/test/java/org/apache/ibatis/binding/FlushTest.java index 462b5e6b0ff..1328a25b22b 100644 --- a/src/test/java/org/apache/ibatis/binding/FlushTest.java +++ b/src/test/java/org/apache/ibatis/binding/FlushTest.java @@ -1,5 +1,5 @@ /** - * Copyright 2009-2015 the original author or authors. + * Copyright 2009-2016 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. @@ -31,9 +31,8 @@ import java.util.ArrayList; import java.util.List; -import static org.hamcrest.core.Is.is; import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertThat; +import static org.assertj.core.api.Assertions.assertThat; public class FlushTest { private static SqlSessionFactory sqlSessionFactory; @@ -75,8 +74,8 @@ public void invokeFlushStatementsViaMapper() { // test List results = mapper.flush(); - assertThat(results.size(), is(1)); - assertThat(results.get(0).getUpdateCounts().length, is(ids.size())); + assertThat(results.size()).isEqualTo(1); + assertThat(results.get(0).getUpdateCounts().length).isEqualTo(ids.size()); for (int id : ids) { Author selectedAuthor = mapper.selectAuthor(id); diff --git a/src/test/java/org/apache/ibatis/builder/ParameterExpressionTest.java b/src/test/java/org/apache/ibatis/builder/ParameterExpressionTest.java index 503769700d2..ba13b43c9a4 100644 --- a/src/test/java/org/apache/ibatis/builder/ParameterExpressionTest.java +++ b/src/test/java/org/apache/ibatis/builder/ParameterExpressionTest.java @@ -1,5 +1,5 @@ /** - * Copyright 2009-2016 the original author or authors. + * Copyright 2009-2017 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. @@ -17,17 +17,10 @@ import java.util.Map; import org.junit.Assert; -import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; - -import static org.hamcrest.core.Is.is; public class ParameterExpressionTest { - @Rule - public ExpectedException expectedException = ExpectedException.none(); - @Test public void simpleProperty() { Map result = new ParameterExpression("id"); @@ -133,16 +126,20 @@ public void shouldIgnoreLeadingAndTrailingSpaces() { @Test public void invalidOldJdbcTypeFormat() { - expectedException.expect(BuilderException.class); - expectedException.expectMessage(is("Parsing error in {id:} in position 3")); - new ParameterExpression("id:"); + try { + new ParameterExpression("id:"); + } catch (BuilderException e) { + e.getMessage().contains("Parsing error in {id:} in position 3"); + } } @Test public void invalidJdbcTypeOptUsingExpression() { - expectedException.expect(BuilderException.class); - expectedException.expectMessage(is("Parsing error in {(expression)+} in position 12")); - new ParameterExpression("(expression)+"); + try { + new ParameterExpression("(expression)+"); + } catch (BuilderException e) { + e.getMessage().contains("Parsing error in {(expression)+} in position 12"); + } } } diff --git a/src/test/java/org/apache/ibatis/builder/XmlConfigBuilderTest.java b/src/test/java/org/apache/ibatis/builder/XmlConfigBuilderTest.java index 2ab3e4ec479..c281d2a0923 100644 --- a/src/test/java/org/apache/ibatis/builder/XmlConfigBuilderTest.java +++ b/src/test/java/org/apache/ibatis/builder/XmlConfigBuilderTest.java @@ -56,18 +56,18 @@ import org.apache.ibatis.type.JdbcType; import org.apache.ibatis.type.TypeHandler; import org.apache.ibatis.type.TypeHandlerRegistry; -import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; -import static org.hamcrest.core.Is.*; -import static org.hamcrest.core.IsInstanceOf.*; -import static org.junit.Assert.*; -public class XmlConfigBuilderTest { +import static com.googlecode.catchexception.apis.BDDCatchException.*; +import static org.assertj.core.api.BDDAssertions.then; +import static org.assertj.core.api.Assertions.assertThat; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertNull; +import static org.junit.Assert.assertTrue; +import static org.junit.Assert.assertArrayEquals; - @Rule - public ExpectedException expectedException = ExpectedException.none(); +public class XmlConfigBuilderTest { @Test public void shouldSuccessfullyLoadMinimalXMLConfigFile() throws Exception { @@ -76,30 +76,31 @@ public void shouldSuccessfullyLoadMinimalXMLConfigFile() throws Exception { XMLConfigBuilder builder = new XMLConfigBuilder(inputStream); Configuration config = builder.parse(); assertNotNull(config); - assertThat(config.getAutoMappingBehavior(), is(AutoMappingBehavior.PARTIAL)); - assertThat(config.getAutoMappingUnknownColumnBehavior(), is(AutoMappingUnknownColumnBehavior.NONE)); - assertThat(config.isCacheEnabled(), is(true)); - assertThat(config.getProxyFactory(), is(instanceOf(JavassistProxyFactory.class))); - assertThat(config.isLazyLoadingEnabled(), is(false)); - assertThat(config.isAggressiveLazyLoading(), is(false)); - assertThat(config.isMultipleResultSetsEnabled(), is(true)); - assertThat(config.isUseColumnLabel(), is(true)); - assertThat(config.isUseGeneratedKeys(), is(false)); - assertThat(config.getDefaultExecutorType(), is(ExecutorType.SIMPLE)); + assertThat(config.getAutoMappingBehavior()).isEqualTo(AutoMappingBehavior.PARTIAL); + assertThat(config.getAutoMappingUnknownColumnBehavior()).isEqualTo(AutoMappingUnknownColumnBehavior.NONE); + assertThat(config.isCacheEnabled()).isTrue(); + assertThat(config.getProxyFactory()).isInstanceOf(JavassistProxyFactory.class); + assertThat(config.isLazyLoadingEnabled()).isFalse(); + assertThat(config.isAggressiveLazyLoading()).isFalse(); + assertThat(config.isMultipleResultSetsEnabled()).isTrue(); + assertThat(config.isUseColumnLabel()).isTrue(); + assertThat(config.isUseGeneratedKeys()).isFalse(); + assertThat(config.getDefaultExecutorType()).isEqualTo(ExecutorType.SIMPLE); assertNull(config.getDefaultStatementTimeout()); assertNull(config.getDefaultFetchSize()); - assertThat(config.isMapUnderscoreToCamelCase(), is(false)); - assertThat(config.isSafeRowBoundsEnabled(), is(false)); - assertThat(config.getLocalCacheScope(), is(LocalCacheScope.SESSION)); - assertThat(config.getJdbcTypeForNull(), is(JdbcType.OTHER)); - assertThat(config.getLazyLoadTriggerMethods(), is((Set) new HashSet(Arrays.asList("equals", "clone", "hashCode", "toString")))); - assertThat(config.isSafeResultHandlerEnabled(), is(true)); - assertThat(config.getDefaultScriptingLanguageInstance(), is(instanceOf(XMLLanguageDriver.class))); - assertThat(config.isCallSettersOnNulls(), is(false)); + assertThat(config.isMapUnderscoreToCamelCase()).isFalse(); + assertThat(config.isSafeRowBoundsEnabled()).isFalse(); + assertThat(config.getLocalCacheScope()).isEqualTo(LocalCacheScope.SESSION); + assertThat(config.getJdbcTypeForNull()).isEqualTo(JdbcType.OTHER); + assertThat(config.getLazyLoadTriggerMethods()).isEqualTo((Set) new HashSet(Arrays.asList("equals", "clone", "hashCode", "toString"))); + assertThat(config.isSafeResultHandlerEnabled()).isTrue(); + assertThat(config.getDefaultScriptingLanuageInstance()).isInstanceOf(XMLLanguageDriver.class); + assertThat(config.isCallSettersOnNulls()).isFalse(); assertNull(config.getLogPrefix()); assertNull(config.getLogImpl()); assertNull(config.getConfigurationFactory()); - assertThat(config.getTypeHandlerRegistry().getTypeHandler(RoundingMode.class), is(instanceOf(EnumTypeHandler.class))); + assertThat(config.getTypeHandlerRegistry().getTypeHandler(RoundingMode.class)).isInstanceOf(EnumTypeHandler.class); + inputStream.close(); } enum MyEnum { @@ -168,66 +169,66 @@ public void shouldSuccessfullyLoadXMLConfigFile() throws Exception { XMLConfigBuilder builder = new XMLConfigBuilder(inputStream, null, props); Configuration config = builder.parse(); - assertThat(config.getAutoMappingBehavior(), is(AutoMappingBehavior.NONE)); - assertThat(config.getAutoMappingUnknownColumnBehavior(), is(AutoMappingUnknownColumnBehavior.WARNING)); - assertThat(config.isCacheEnabled(), is(false)); - assertThat(config.getProxyFactory(), is(instanceOf(CglibProxyFactory.class))); - assertThat(config.isLazyLoadingEnabled(), is(true)); - assertThat(config.isAggressiveLazyLoading(), is(true)); - assertThat(config.isMultipleResultSetsEnabled(), is(false)); - assertThat(config.isUseColumnLabel(), is(false)); - assertThat(config.isUseGeneratedKeys(), is(true)); - assertThat(config.getDefaultExecutorType(), is(ExecutorType.BATCH)); - assertThat(config.getDefaultStatementTimeout(), is(10)); - assertThat(config.getDefaultFetchSize(), is(100)); - assertThat(config.isMapUnderscoreToCamelCase(), is(true)); - assertThat(config.isSafeRowBoundsEnabled(), is(true)); - assertThat(config.getLocalCacheScope(), is(LocalCacheScope.STATEMENT)); - assertThat(config.getJdbcTypeForNull(), is(JdbcType.NULL)); - assertThat(config.getLazyLoadTriggerMethods(), is((Set) new HashSet(Arrays.asList("equals", "clone", "hashCode", "toString", "xxx")))); - assertThat(config.isSafeResultHandlerEnabled(), is(false)); - assertThat(config.getDefaultScriptingLanguageInstance(), is(instanceOf(RawLanguageDriver.class))); - assertThat(config.isCallSettersOnNulls(), is(true)); - assertThat(config.getLogPrefix(), is("mybatis_")); - assertThat(config.getLogImpl().getName(), is(Slf4jImpl.class.getName())); - assertThat(config.getVfsImpl().getName(), is(JBoss6VFS.class.getName())); - assertThat(config.getConfigurationFactory().getName(), is(String.class.getName())); + assertThat(config.getAutoMappingBehavior()).isEqualTo(AutoMappingBehavior.NONE); + assertThat(config.getAutoMappingUnknownColumnBehavior()).isEqualTo(AutoMappingUnknownColumnBehavior.WARNING); + assertThat(config.isCacheEnabled()).isFalse(); + assertThat(config.getProxyFactory()).isInstanceOf(CglibProxyFactory.class); + assertThat(config.isLazyLoadingEnabled()).isTrue(); + assertThat(config.isAggressiveLazyLoading()).isTrue(); + assertThat(config.isMultipleResultSetsEnabled()).isFalse(); + assertThat(config.isUseColumnLabel()).isFalse(); + assertThat(config.isUseGeneratedKeys()).isTrue(); + assertThat(config.getDefaultExecutorType()).isEqualTo(ExecutorType.BATCH); + assertThat(config.getDefaultStatementTimeout()).isEqualTo(10); + assertThat(config.getDefaultFetchSize()).isEqualTo(100); + assertThat(config.isMapUnderscoreToCamelCase()).isTrue(); + assertThat(config.isSafeRowBoundsEnabled()).isTrue(); + assertThat(config.getLocalCacheScope()).isEqualTo(LocalCacheScope.STATEMENT); + assertThat(config.getJdbcTypeForNull()).isEqualTo(JdbcType.NULL); + assertThat(config.getLazyLoadTriggerMethods()).isEqualTo((Set) new HashSet(Arrays.asList("equals", "clone", "hashCode", "toString", "xxx"))); + assertThat(config.isSafeResultHandlerEnabled()).isFalse(); + assertThat(config.getDefaultScriptingLanuageInstance()).isInstanceOf(RawLanguageDriver.class); + assertThat(config.isCallSettersOnNulls()).isTrue(); + assertThat(config.getLogPrefix()).isEqualTo("mybatis_"); + assertThat(config.getLogImpl().getName()).isEqualTo(Slf4jImpl.class.getName()); + assertThat(config.getVfsImpl().getName()).isEqualTo(JBoss6VFS.class.getName()); + assertThat(config.getConfigurationFactory().getName()).isEqualTo(String.class.getName()); assertTrue(config.getTypeAliasRegistry().getTypeAliases().get("blogauthor").equals(Author.class)); assertTrue(config.getTypeAliasRegistry().getTypeAliases().get("blog").equals(Blog.class)); assertTrue(config.getTypeAliasRegistry().getTypeAliases().get("cart").equals(Cart.class)); - assertThat(config.getTypeHandlerRegistry().getTypeHandler(Integer.class), is(instanceOf(CustomIntegerTypeHandler.class))); - assertThat(config.getTypeHandlerRegistry().getTypeHandler(Long.class), is(instanceOf(CustomLongTypeHandler.class))); - assertThat(config.getTypeHandlerRegistry().getTypeHandler(String.class), is(instanceOf(CustomStringTypeHandler.class))); - assertThat(config.getTypeHandlerRegistry().getTypeHandler(String.class, JdbcType.VARCHAR), is(instanceOf(CustomStringTypeHandler.class))); - assertThat(config.getTypeHandlerRegistry().getTypeHandler(RoundingMode.class), is(instanceOf(EnumOrdinalTypeHandler.class))); + assertThat(config.getTypeHandlerRegistry().getTypeHandler(Integer.class)).isInstanceOf(CustomIntegerTypeHandler.class); + assertThat(config.getTypeHandlerRegistry().getTypeHandler(Long.class)).isInstanceOf(CustomLongTypeHandler.class); + assertThat(config.getTypeHandlerRegistry().getTypeHandler(String.class)).isInstanceOf(CustomStringTypeHandler.class); + assertThat(config.getTypeHandlerRegistry().getTypeHandler(String.class, JdbcType.VARCHAR)).isInstanceOf(CustomStringTypeHandler.class); + assertThat(config.getTypeHandlerRegistry().getTypeHandler(RoundingMode.class)).isInstanceOf(EnumOrdinalTypeHandler.class); ExampleObjectFactory objectFactory = (ExampleObjectFactory)config.getObjectFactory(); - assertThat(objectFactory.getProperties().size(), is(1)); - assertThat(objectFactory.getProperties().getProperty("objectFactoryProperty"), is("100")); + assertThat(objectFactory.getProperties().size()).isEqualTo(1); + assertThat(objectFactory.getProperties().getProperty("objectFactoryProperty")).isEqualTo("100"); - assertThat(config.getObjectWrapperFactory(), is(instanceOf(CustomObjectWrapperFactory.class))); + assertThat(config.getObjectWrapperFactory()).isInstanceOf(CustomObjectWrapperFactory.class); - assertThat(config.getReflectorFactory(), is(instanceOf(CustomReflectorFactory.class))); + assertThat(config.getReflectorFactory()).isInstanceOf(CustomReflectorFactory.class); ExamplePlugin plugin = (ExamplePlugin)config.getInterceptors().get(0); - assertThat(plugin.getProperties().size(), is(1)); - assertThat(plugin.getProperties().getProperty("pluginProperty"), is("100")); + assertThat(plugin.getProperties().size()).isEqualTo(1); + assertThat(plugin.getProperties().getProperty("pluginProperty")).isEqualTo("100"); Environment environment = config.getEnvironment(); - assertThat(environment.getId(), is("development")); - assertThat(environment.getDataSource(), is(instanceOf(UnpooledDataSource.class))); - assertThat(environment.getTransactionFactory(), is(instanceOf(JdbcTransactionFactory.class))); - - assertThat(config.getDatabaseId(), is("derby")); - - assertThat(config.getMapperRegistry().getMappers().size(), is(4)); - assertThat(config.getMapperRegistry().hasMapper(CachedAuthorMapper.class), is(true)); - assertThat(config.getMapperRegistry().hasMapper(CustomMapper.class), is(true)); - assertThat(config.getMapperRegistry().hasMapper(BlogMapper.class), is(true)); - assertThat(config.getMapperRegistry().hasMapper(NestedBlogMapper.class), is(true)); - + assertThat(environment.getId()).isEqualTo("development"); + assertThat(environment.getDataSource()).isInstanceOf(UnpooledDataSource.class); + assertThat(environment.getTransactionFactory()).isInstanceOf(JdbcTransactionFactory.class); + + assertThat(config.getDatabaseId()).isEqualTo("derby"); + + assertThat(config.getMapperRegistry().getMappers().size()).isEqualTo(4); + assertThat(config.getMapperRegistry().hasMapper(CachedAuthorMapper.class)).isTrue(); + assertThat(config.getMapperRegistry().hasMapper(CustomMapper.class)).isTrue(); + assertThat(config.getMapperRegistry().hasMapper(BlogMapper.class)).isTrue(); + assertThat(config.getMapperRegistry().hasMapper(NestedBlogMapper.class)).isTrue(); + inputStream.close(); } @Test @@ -236,9 +237,9 @@ public void shouldSuccessfullyLoadXMLConfigFileWithPropertiesUrl() throws Except InputStream inputStream = Resources.getResourceAsStream(resource); XMLConfigBuilder builder = new XMLConfigBuilder(inputStream); Configuration config = builder.parse(); - assertThat(config.getVariables().get("driver").toString(), is("org.apache.derby.jdbc.EmbeddedDriver")); - assertThat(config.getVariables().get("prop1").toString(), is("bbbb")); - + assertThat(config.getVariables().get("driver").toString()).isEqualTo("org.apache.derby.jdbc.EmbeddedDriver"); + assertThat(config.getVariables().get("prop1").toString()).isEqualTo("bbbb"); + inputStream.close(); } @Test @@ -248,9 +249,10 @@ public void parseIsTwice() throws Exception { XMLConfigBuilder builder = new XMLConfigBuilder(inputStream); builder.parse(); - expectedException.expect(BuilderException.class); - expectedException.expectMessage("Each XMLConfigBuilder can only be used once."); - builder.parse(); + when(builder).parse(); + then(caughtException()).isInstanceOf(BuilderException.class) + .hasMessage("Each XMLConfigBuilder can only be used once."); + inputStream.close(); } @Test @@ -263,11 +265,10 @@ public void unknownSettings() { + " \n" + "\n"; - expectedException.expect(BuilderException.class); - expectedException.expectMessage("The setting foo is not known. Make sure you spelled it correctly (case sensitive)."); - XMLConfigBuilder builder = new XMLConfigBuilder(new StringReader(MAPPER_CONFIG)); - builder.parse(); + when(builder).parse(); + then(caughtException()).isInstanceOf(BuilderException.class) + .hasMessageContaining("The setting foo is not known. Make sure you spelled it correctly (case sensitive)."); } @Test @@ -280,11 +281,10 @@ public void unknownJavaTypeOnTypeHandler() { + " \n" + "\n"; - expectedException.expect(BuilderException.class); - expectedException.expectMessage("Error registering typeAlias for 'null'. Cause: "); - XMLConfigBuilder builder = new XMLConfigBuilder(new StringReader(MAPPER_CONFIG)); - builder.parse(); + when(builder).parse(); + then(caughtException()).isInstanceOf(BuilderException.class) + .hasMessageContaining("Error registering typeAlias for 'null'. Cause: "); } @Test @@ -295,11 +295,10 @@ public void propertiesSpecifyResourceAndUrlAtSameTime() { + " \n" + "\n"; - expectedException.expect(BuilderException.class); - expectedException.expectMessage("The properties element cannot specify both a URL and a resource based property file reference. Please specify one or the other."); - XMLConfigBuilder builder = new XMLConfigBuilder(new StringReader(MAPPER_CONFIG)); - builder.parse(); + when(builder).parse(); + then(caughtException()).isInstanceOf(BuilderException.class) + .hasMessageContaining("The properties element cannot specify both a URL and a resource based property file reference. Please specify one or the other."); } } diff --git a/src/test/java/org/apache/ibatis/builder/XmlMapperBuilderTest.java b/src/test/java/org/apache/ibatis/builder/XmlMapperBuilderTest.java index e972ddf1611..5719eda30aa 100644 --- a/src/test/java/org/apache/ibatis/builder/XmlMapperBuilderTest.java +++ b/src/test/java/org/apache/ibatis/builder/XmlMapperBuilderTest.java @@ -1,5 +1,5 @@ /** - * Copyright 2009-2016 the original author or authors. + * Copyright 2009-2017 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. @@ -25,17 +25,14 @@ import org.apache.ibatis.mapping.StatementType; import org.apache.ibatis.session.Configuration; import org.apache.ibatis.type.TypeHandler; -import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; -import static org.junit.Assert.assertThat; -import static org.hamcrest.CoreMatchers.*; +import static com.googlecode.catchexception.apis.BDDCatchException.*; +import static org.assertj.core.api.BDDAssertions.then; -public class XmlMapperBuilderTest { +import static org.assertj.core.api.Assertions.assertThat; - @Rule - public ExpectedException expectedException = ExpectedException.none(); +public class XmlMapperBuilderTest { @Test public void shouldSuccessfullyLoadXMLMapperFile() throws Exception { @@ -44,6 +41,7 @@ public void shouldSuccessfullyLoadXMLMapperFile() throws Exception { InputStream inputStream = Resources.getResourceAsStream(resource); XMLMapperBuilder builder = new XMLMapperBuilder(inputStream, configuration, resource, configuration.getSqlFragments()); builder.parse(); + inputStream.close(); } @Test @@ -55,13 +53,13 @@ public void mappedStatementWithOptions() throws Exception { builder.parse(); MappedStatement mappedStatement = configuration.getMappedStatement("selectWithOptions"); - assertThat(mappedStatement.getFetchSize(), is(200)); - assertThat(mappedStatement.getTimeout(), is(10)); - assertThat(mappedStatement.getStatementType(), is(StatementType.PREPARED)); - assertThat(mappedStatement.getResultSetType(), is(ResultSetType.SCROLL_SENSITIVE)); - assertThat(mappedStatement.isFlushCacheRequired(), is(false)); - assertThat(mappedStatement.isUseCache(), is(false)); - + assertThat(mappedStatement.getFetchSize()).isEqualTo(200); + assertThat(mappedStatement.getTimeout()).isEqualTo(10); + assertThat(mappedStatement.getStatementType()).isEqualTo(StatementType.PREPARED); + assertThat(mappedStatement.getResultSetType()).isEqualTo(ResultSetType.SCROLL_SENSITIVE); + assertThat(mappedStatement.isFlushCacheRequired()).isFalse(); + assertThat(mappedStatement.isUseCache()).isFalse(); + inputStream.close(); } @Test @@ -69,96 +67,104 @@ public void parseExpression() { BaseBuilder builder = new BaseBuilder(new Configuration()){{}}; { Pattern pattern = builder.parseExpression("[0-9]", "[a-z]"); - assertThat(pattern.matcher("0").find(), is(true)); - assertThat(pattern.matcher("a").find(), is(false)); + assertThat(pattern.matcher("0").find()).isTrue(); + assertThat(pattern.matcher("a").find()).isFalse(); } { Pattern pattern = builder.parseExpression(null, "[a-z]"); - assertThat(pattern.matcher("0").find(), is(false)); - assertThat(pattern.matcher("a").find(), is(true)); + assertThat(pattern.matcher("0").find()).isFalse(); + assertThat(pattern.matcher("a").find()).isTrue(); } } @Test public void resolveJdbcTypeWithUndefinedValue() { BaseBuilder builder = new BaseBuilder(new Configuration()){{}}; - expectedException.expect(BuilderException.class); - expectedException.expectMessage(startsWith("Error resolving JdbcType. Cause: java.lang.IllegalArgumentException: No enum")); - expectedException.expectMessage(endsWith("org.apache.ibatis.type.JdbcType.aaa")); - builder.resolveJdbcType("aaa"); + when(builder).resolveJdbcType("aaa"); + then(caughtException()) + .isInstanceOf(BuilderException.class) + .hasMessageStartingWith("Error resolving JdbcType. Cause: java.lang.IllegalArgumentException: No enum") + .hasMessageEndingWith("org.apache.ibatis.type.JdbcType.aaa"); } @Test public void resolveResultSetTypeWithUndefinedValue() { BaseBuilder builder = new BaseBuilder(new Configuration()){{}}; - expectedException.expect(BuilderException.class); - expectedException.expectMessage(startsWith("Error resolving ResultSetType. Cause: java.lang.IllegalArgumentException: No enum")); - expectedException.expectMessage(endsWith("org.apache.ibatis.mapping.ResultSetType.bbb")); - builder.resolveResultSetType("bbb"); + when(builder).resolveResultSetType("bbb"); + then(caughtException()) + .isInstanceOf(BuilderException.class) + .hasMessageStartingWith("Error resolving ResultSetType. Cause: java.lang.IllegalArgumentException: No enum") + .hasMessageEndingWith("org.apache.ibatis.mapping.ResultSetType.bbb"); } @Test public void resolveParameterModeWithUndefinedValue() { BaseBuilder builder = new BaseBuilder(new Configuration()){{}}; - expectedException.expect(BuilderException.class); - expectedException.expectMessage(startsWith("Error resolving ParameterMode. Cause: java.lang.IllegalArgumentException: No enum")); - expectedException.expectMessage(endsWith("org.apache.ibatis.mapping.ParameterMode.ccc")); - builder.resolveParameterMode("ccc"); + when(builder).resolveParameterMode("ccc"); + then(caughtException()) + .isInstanceOf(BuilderException.class) + .hasMessageStartingWith("Error resolving ParameterMode. Cause: java.lang.IllegalArgumentException: No enum") + .hasMessageEndingWith("org.apache.ibatis.mapping.ParameterMode.ccc"); } @Test public void createInstanceWithAbstractClass() { BaseBuilder builder = new BaseBuilder(new Configuration()){{}}; - expectedException.expect(BuilderException.class); - expectedException.expectMessage(is("Error creating instance. Cause: java.lang.InstantiationException: org.apache.ibatis.builder.BaseBuilder")); - builder.createInstance("org.apache.ibatis.builder.BaseBuilder"); + when(builder).createInstance("org.apache.ibatis.builder.BaseBuilder"); + then(caughtException()) + .isInstanceOf(BuilderException.class) + .hasMessage("Error creating instance. Cause: java.lang.InstantiationException: org.apache.ibatis.builder.BaseBuilder"); } @Test public void resolveClassWithNotFound() { BaseBuilder builder = new BaseBuilder(new Configuration()){{}}; - expectedException.expect(BuilderException.class); - expectedException.expectMessage(is("Error resolving class. Cause: org.apache.ibatis.type.TypeException: Could not resolve type alias 'ddd'. Cause: java.lang.ClassNotFoundException: Cannot find class: ddd")); - builder.resolveClass("ddd"); + when(builder).resolveClass("ddd"); + then(caughtException()) + .isInstanceOf(BuilderException.class) + .hasMessage("Error resolving class. Cause: org.apache.ibatis.type.TypeException: Could not resolve type alias 'ddd'. Cause: java.lang.ClassNotFoundException: Cannot find class: ddd"); } @Test public void resolveTypeHandlerTypeHandlerAliasIsNull() { BaseBuilder builder = new BaseBuilder(new Configuration()){{}}; TypeHandler typeHandler = builder.resolveTypeHandler(String.class, (String)null); - assertThat(typeHandler, nullValue()); + assertThat(typeHandler).isNull(); } @Test public void resolveTypeHandlerNoAssignable() { BaseBuilder builder = new BaseBuilder(new Configuration()){{}}; - expectedException.expect(BuilderException.class); - expectedException.expectMessage(is("Type java.lang.Integer is not a valid TypeHandler because it does not implement TypeHandler interface")); - builder.resolveTypeHandler(String.class, "integer"); + when(builder).resolveTypeHandler(String.class, "integer"); + then(caughtException()) + .isInstanceOf(BuilderException.class) + .hasMessage("Type java.lang.Integer is not a valid TypeHandler because it does not implement TypeHandler interface"); } @Test public void setCurrentNamespaceValueIsNull() { MapperBuilderAssistant builder = new MapperBuilderAssistant(new Configuration(), "resource"); - expectedException.expect(BuilderException.class); - expectedException.expectMessage(is("The mapper element requires a namespace attribute to be specified.")); - builder.setCurrentNamespace(null); + when(builder).setCurrentNamespace(null); + then(caughtException()) + .isInstanceOf(BuilderException.class) + .hasMessage("The mapper element requires a namespace attribute to be specified."); } @Test public void useCacheRefNamespaceIsNull() { MapperBuilderAssistant builder = new MapperBuilderAssistant(new Configuration(), "resource"); - expectedException.expect(BuilderException.class); - expectedException.expectMessage(is("cache-ref element requires a namespace attribute.")); - builder.useCacheRef(null); + when(builder).useCacheRef(null); + then(caughtException()) + .isInstanceOf(BuilderException.class) + .hasMessage("cache-ref element requires a namespace attribute."); } @Test public void useCacheRefNamespaceIsUndefined() { MapperBuilderAssistant builder = new MapperBuilderAssistant(new Configuration(), "resource"); - expectedException.expect(IncompleteElementException.class); - expectedException.expectMessage(is("No cache for namespace 'eee' could be found.")); - builder.useCacheRef("eee"); + when(builder).useCacheRef("eee"); + then(caughtException()) + .hasMessage("No cache for namespace 'eee' could be found."); } // @Test diff --git a/src/test/java/org/apache/ibatis/executor/ResultExtractorTest.java b/src/test/java/org/apache/ibatis/executor/ResultExtractorTest.java index d8514c3f5f3..85ebb288e91 100644 --- a/src/test/java/org/apache/ibatis/executor/ResultExtractorTest.java +++ b/src/test/java/org/apache/ibatis/executor/ResultExtractorTest.java @@ -26,8 +26,7 @@ import java.util.*; -import static org.hamcrest.CoreMatchers.*; -import static org.junit.Assert.assertThat; +import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.Mockito.*; @RunWith(MockitoJUnitRunner.class) @@ -48,25 +47,25 @@ public void setUp() throws Exception { @Test public void shouldExtractNullForNullTargetType() { final Object result = resultExtractor.extractObjectFromList(null, null); - assertThat(result, nullValue()); + assertThat(result).isNull(); } @Test public void shouldExtractList() { final List list = Arrays.asList(1, 2, 3); final Object result = resultExtractor.extractObjectFromList(list, List.class); - assertThat(result, instanceOf(List.class)); + assertThat(result).isInstanceOf(List.class); final List resultList = (List) result; - assertThat(resultList, equalTo(list)); + assertThat(resultList).isEqualTo(list); } @Test public void shouldExtractArray() { final List list = Arrays.asList(1, 2, 3); final Object result = resultExtractor.extractObjectFromList(list, Integer[].class); - assertThat(result, instanceOf(Integer[].class)); + assertThat(result).isInstanceOf(Integer[].class); final Integer[] resultArray = (Integer[]) result; - assertThat(resultArray, equalTo(new Integer[]{1, 2, 3})); + assertThat(resultArray).isEqualTo(new Integer[]{1, 2, 3}); } @Test @@ -80,7 +79,7 @@ public void shouldExtractSet() { when(configuration.newMetaObject(set)).thenReturn(metaObject); final Set result = (Set) resultExtractor.extractObjectFromList(list, targetType); - assertThat(result, sameInstance(set)); + assertThat(result).isSameAs(set); verify(metaObject).addAll(list); } @@ -88,14 +87,14 @@ public void shouldExtractSet() { @Test public void shouldExtractSingleObject() { final List list = Collections.singletonList("single object"); - assertThat((String) resultExtractor.extractObjectFromList(list, String.class), equalTo("single object")); - assertThat((String) resultExtractor.extractObjectFromList(list, null), equalTo("single object")); - assertThat((String) resultExtractor.extractObjectFromList(list, Integer.class), equalTo("single object")); + assertThat((String) resultExtractor.extractObjectFromList(list, String.class)).isEqualTo("single object"); + assertThat((String) resultExtractor.extractObjectFromList(list, null)).isEqualTo("single object"); + assertThat((String) resultExtractor.extractObjectFromList(list, Integer.class)).isEqualTo("single object"); } @Test(expected = ExecutorException.class) public void shouldFailWhenMutipleItemsInList() { final List list = Arrays.asList("first object", "second object"); - assertThat((String) resultExtractor.extractObjectFromList(list, String.class), equalTo("single object")); + assertThat((String) resultExtractor.extractObjectFromList(list, String.class)).isEqualTo("single object"); } } diff --git a/src/test/java/org/apache/ibatis/jdbc/SQLTest.java b/src/test/java/org/apache/ibatis/jdbc/SQLTest.java index 5620ffb90e9..c1e7a74ae13 100644 --- a/src/test/java/org/apache/ibatis/jdbc/SQLTest.java +++ b/src/test/java/org/apache/ibatis/jdbc/SQLTest.java @@ -15,11 +15,10 @@ */ package org.apache.ibatis.jdbc; -import org.hamcrest.CoreMatchers; import org.junit.Test; +import static org.assertj.core.api.Assertions.assertThat; import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertThat; public class SQLTest { @@ -302,6 +301,6 @@ public void variableLengthArgumentOnIntoColumnsAndValues() { @Test public void fixFor903UpdateJoins() { final SQL sql = new SQL().UPDATE("table1 a").INNER_JOIN("table2 b USING (ID)").SET("a.value = b.value"); - assertThat(sql.toString(), CoreMatchers.equalTo("UPDATE table1 a\nINNER JOIN table2 b USING (ID)\nSET a.value = b.value")); + assertThat(sql.toString()).isEqualTo("UPDATE table1 a\nINNER JOIN table2 b USING (ID)\nSET a.value = b.value"); } } diff --git a/src/test/java/org/apache/ibatis/logging/jdbc/BaseJdbcLoggerTest.java b/src/test/java/org/apache/ibatis/logging/jdbc/BaseJdbcLoggerTest.java index 6a22ace002a..f53e949f105 100644 --- a/src/test/java/org/apache/ibatis/logging/jdbc/BaseJdbcLoggerTest.java +++ b/src/test/java/org/apache/ibatis/logging/jdbc/BaseJdbcLoggerTest.java @@ -1,5 +1,5 @@ /** - * Copyright 2009-2016 the original author or authors. + * Copyright 2009-2017 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. @@ -16,7 +16,6 @@ package org.apache.ibatis.logging.jdbc; import org.apache.ibatis.logging.Log; -import org.hamcrest.core.StringStartsWith; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; @@ -25,7 +24,7 @@ import java.sql.Array; -import static org.junit.Assert.assertThat; +import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.Mockito.when; @RunWith(MockitoJUnitRunner.class) @@ -47,14 +46,13 @@ public void setUp() throws Exception { public void shouldDescribePrimitiveArrayParameter() throws Exception { logger.setColumn("1", array); when(array.getArray()).thenReturn(new int[] { 1, 2, 3 }); - assertThat(logger.getParameterValueString(), StringStartsWith.startsWith("[1, 2, 3]")); + assertThat(logger.getParameterValueString()).startsWith("[1, 2, 3]"); } @Test public void shouldDescribeObjectArrayParameter() throws Exception { logger.setColumn("1", array); when(array.getArray()).thenReturn(new String[] { "one", "two", "three" }); - assertThat(logger.getParameterValueString(), - StringStartsWith.startsWith("[one, two, three]")); + assertThat(logger.getParameterValueString()).startsWith("[one, two, three]"); } } \ No newline at end of file diff --git a/src/test/java/org/apache/ibatis/mapping/CacheBuilderTest.java b/src/test/java/org/apache/ibatis/mapping/CacheBuilderTest.java index 4f55ae1fac6..6e7b42557fe 100644 --- a/src/test/java/org/apache/ibatis/mapping/CacheBuilderTest.java +++ b/src/test/java/org/apache/ibatis/mapping/CacheBuilderTest.java @@ -1,5 +1,5 @@ /** - * Copyright 2009-2016 the original author or authors. + * Copyright 2009-2017 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. @@ -19,32 +19,28 @@ import org.apache.ibatis.cache.Cache; import org.apache.ibatis.cache.CacheException; import org.apache.ibatis.cache.impl.PerpetualCache; -import org.hamcrest.core.Is; -import org.junit.Assert; -import org.junit.Rule; +import org.assertj.core.api.Assertions; import org.junit.Test; -import org.junit.rules.ExpectedException; import java.lang.reflect.Field; -public class CacheBuilderTest { +import static com.googlecode.catchexception.apis.BDDCatchException.*; +import static org.assertj.core.api.BDDAssertions.then; - @Rule - public ExpectedException expectedException = ExpectedException.none(); +public class CacheBuilderTest { @Test public void testInitializing() throws Exception { InitializingCache cache = unwrap(new CacheBuilder("test").implementation(InitializingCache.class).build()); - Assert.assertThat(cache.initialized, Is.is(true)); + Assertions.assertThat(cache.initialized).isTrue(); } @Test public void testInitializingFailure() throws Exception { - expectedException.expect(CacheException.class); - expectedException.expectMessage("Failed cache initialization for 'test' on 'org.apache.ibatis.mapping.CacheBuilderTest$InitializingFailureCache'"); - - new CacheBuilder("test").implementation(InitializingFailureCache.class).build(); + when(new CacheBuilder("test").implementation(InitializingFailureCache.class)).build(); + then(caughtException()).isInstanceOf(CacheException.class) + .hasMessage("Failed cache initialization for 'test' on 'org.apache.ibatis.mapping.CacheBuilderTest$InitializingFailureCache'"); } @SuppressWarnings("unchecked") diff --git a/src/test/java/org/apache/ibatis/parsing/PropertyParserTest.java b/src/test/java/org/apache/ibatis/parsing/PropertyParserTest.java index c7549c51b87..272154c24fe 100644 --- a/src/test/java/org/apache/ibatis/parsing/PropertyParserTest.java +++ b/src/test/java/org/apache/ibatis/parsing/PropertyParserTest.java @@ -1,5 +1,5 @@ /** - * Copyright 2009-2016 the original author or authors. + * Copyright 2009-2017 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. @@ -15,8 +15,7 @@ */ package org.apache.ibatis.parsing; -import org.hamcrest.core.Is; -import org.junit.Assert; +import org.assertj.core.api.Assertions; import org.junit.Test; import java.util.Properties; @@ -31,15 +30,15 @@ public void replaceToVariableValue() { props.setProperty("tableName", "members"); props.setProperty("orderColumn", "member_id"); props.setProperty("a:b", "c"); - Assert.assertThat(PropertyParser.parse("${key}", props), Is.is("value")); - Assert.assertThat(PropertyParser.parse("${key:aaaa}", props), Is.is("value")); - Assert.assertThat(PropertyParser.parse("SELECT * FROM ${tableName:users} ORDER BY ${orderColumn:id}", props), Is.is("SELECT * FROM members ORDER BY member_id")); + Assertions.assertThat(PropertyParser.parse("${key}", props)).isEqualTo("value"); + Assertions.assertThat(PropertyParser.parse("${key:aaaa}", props)).isEqualTo("value"); + Assertions.assertThat(PropertyParser.parse("SELECT * FROM ${tableName:users} ORDER BY ${orderColumn:id}", props)).isEqualTo("SELECT * FROM members ORDER BY member_id"); props.setProperty(PropertyParser.KEY_ENABLE_DEFAULT_VALUE, "false"); - Assert.assertThat(PropertyParser.parse("${a:b}", props), Is.is("c")); + Assertions.assertThat(PropertyParser.parse("${a:b}", props)).isEqualTo("c"); props.remove(PropertyParser.KEY_ENABLE_DEFAULT_VALUE); - Assert.assertThat(PropertyParser.parse("${a:b}", props), Is.is("c")); + Assertions.assertThat(PropertyParser.parse("${a:b}", props)).isEqualTo("c"); } @@ -47,14 +46,14 @@ public void replaceToVariableValue() { public void notReplace() { Properties props = new Properties(); props.setProperty(PropertyParser.KEY_ENABLE_DEFAULT_VALUE, "true"); - Assert.assertThat(PropertyParser.parse("${key}", props), Is.is("${key}")); - Assert.assertThat(PropertyParser.parse("${key}", null), Is.is("${key}")); + Assertions.assertThat(PropertyParser.parse("${key}", props)).isEqualTo("${key}"); + Assertions.assertThat(PropertyParser.parse("${key}", null)).isEqualTo("${key}"); props.setProperty(PropertyParser.KEY_ENABLE_DEFAULT_VALUE, "false"); - Assert.assertThat(PropertyParser.parse("${a:b}", props), Is.is("${a:b}")); + Assertions.assertThat(PropertyParser.parse("${a:b}", props)).isEqualTo("${a:b}"); props.remove(PropertyParser.KEY_ENABLE_DEFAULT_VALUE); - Assert.assertThat(PropertyParser.parse("${a:b}", props), Is.is("${a:b}")); + Assertions.assertThat(PropertyParser.parse("${a:b}", props)).isEqualTo("${a:b}"); } @@ -62,11 +61,11 @@ public void notReplace() { public void applyDefaultValue() { Properties props = new Properties(); props.setProperty(PropertyParser.KEY_ENABLE_DEFAULT_VALUE, "true"); - Assert.assertThat(PropertyParser.parse("${key:default}", props), Is.is("default")); - Assert.assertThat(PropertyParser.parse("SELECT * FROM ${tableName:users} ORDER BY ${orderColumn:id}", props), Is.is("SELECT * FROM users ORDER BY id")); - Assert.assertThat(PropertyParser.parse("${key:}", props), Is.is("")); - Assert.assertThat(PropertyParser.parse("${key: }", props), Is.is(" ")); - Assert.assertThat(PropertyParser.parse("${key::}", props), Is.is(":")); + Assertions.assertThat(PropertyParser.parse("${key:default}", props)).isEqualTo("default"); + Assertions.assertThat(PropertyParser.parse("SELECT * FROM ${tableName:users} ORDER BY ${orderColumn:id}", props)).isEqualTo("SELECT * FROM users ORDER BY id"); + Assertions.assertThat(PropertyParser.parse("${key:}", props)).isEmpty(); + Assertions.assertThat(PropertyParser.parse("${key: }", props)).isEqualTo(" "); + Assertions.assertThat(PropertyParser.parse("${key::}", props)).isEqualTo(":"); } @Test @@ -74,11 +73,11 @@ public void applyCustomSeparator() { Properties props = new Properties(); props.setProperty(PropertyParser.KEY_ENABLE_DEFAULT_VALUE, "true"); props.setProperty(PropertyParser.KEY_DEFAULT_VALUE_SEPARATOR, "?:"); - Assert.assertThat(PropertyParser.parse("${key?:default}", props), Is.is("default")); - Assert.assertThat(PropertyParser.parse("SELECT * FROM ${schema?:prod}.${tableName == null ? 'users' : tableName} ORDER BY ${orderColumn}", props), Is.is("SELECT * FROM prod.${tableName == null ? 'users' : tableName} ORDER BY ${orderColumn}")); - Assert.assertThat(PropertyParser.parse("${key?:}", props), Is.is("")); - Assert.assertThat(PropertyParser.parse("${key?: }", props), Is.is(" ")); - Assert.assertThat(PropertyParser.parse("${key?::}", props), Is.is(":")); + Assertions.assertThat(PropertyParser.parse("${key?:default}", props)).isEqualTo("default"); + Assertions.assertThat(PropertyParser.parse("SELECT * FROM ${schema?:prod}.${tableName == null ? 'users' : tableName} ORDER BY ${orderColumn}", props)).isEqualTo("SELECT * FROM prod.${tableName == null ? 'users' : tableName} ORDER BY ${orderColumn}"); + Assertions.assertThat(PropertyParser.parse("${key?:}", props)).isEmpty(); + Assertions.assertThat(PropertyParser.parse("${key?: }", props)).isEqualTo(" "); + Assertions.assertThat(PropertyParser.parse("${key?::}", props)).isEqualTo(":"); } } diff --git a/src/test/java/org/apache/ibatis/reflection/ReflectorTest.java b/src/test/java/org/apache/ibatis/reflection/ReflectorTest.java index 1218f2fe8bd..53c275fbae9 100644 --- a/src/test/java/org/apache/ibatis/reflection/ReflectorTest.java +++ b/src/test/java/org/apache/ibatis/reflection/ReflectorTest.java @@ -15,22 +15,18 @@ */ package org.apache.ibatis.reflection; -import static org.hamcrest.CoreMatchers.*; import static org.junit.Assert.*; import java.io.Serializable; import java.util.List; import org.junit.Assert; -import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; +import static com.googlecode.catchexception.apis.BDDCatchException.*; +import static org.assertj.core.api.BDDAssertions.then; public class ReflectorTest { - @Rule - public ExpectedException expectedException = ExpectedException.none(); - @Test public void testGetSetterType() throws Exception { ReflectorFactory reflectorFactory = new DefaultReflectorFactory(); @@ -170,7 +166,10 @@ static class Child extends Parent { @Test public void shouldResoleveReadonlySetterWithOverload() throws Exception { class BeanClass implements BeanInterface { - public void setId(String id) {} + @Override + public void setId(String id) { + // Do nothing + } } ReflectorFactory reflectorFactory = new DefaultReflectorFactory(); Reflector reflector = reflectorFactory.findForClass(BeanClass.class); @@ -188,15 +187,14 @@ class BeanClass { public void setTheProp(String arg) {} public void setTheProp(Integer arg) {} } - expectedException.expect(ReflectionException.class); - expectedException.expectMessage(allOf( - containsString("theProp"), - containsString("BeanClass"), - containsString("java.lang.String"), - containsString("java.lang.Integer"))); + ReflectorFactory reflectorFactory = new DefaultReflectorFactory(); - Reflector reflector = reflectorFactory.findForClass(BeanClass.class); - reflector.getSetterType("theProp"); + when(reflectorFactory).findForClass(BeanClass.class); + then(caughtException()).isInstanceOf(ReflectionException.class) + .hasMessageContaining("theProp") + .hasMessageContaining("BeanClass") + .hasMessageContaining("java.lang.String") + .hasMessageContaining("java.lang.Integer"); } @Test diff --git a/src/test/java/org/apache/ibatis/scripting/LanguageDriverRegistryTest.java b/src/test/java/org/apache/ibatis/scripting/LanguageDriverRegistryTest.java index 3505d7e200f..bbec82c36d8 100644 --- a/src/test/java/org/apache/ibatis/scripting/LanguageDriverRegistryTest.java +++ b/src/test/java/org/apache/ibatis/scripting/LanguageDriverRegistryTest.java @@ -15,6 +15,8 @@ */ package org.apache.ibatis.scripting; +import static org.assertj.core.api.Assertions.assertThat; + import org.apache.ibatis.executor.parameter.ParameterHandler; import org.apache.ibatis.mapping.BoundSql; import org.apache.ibatis.mapping.MappedStatement; @@ -22,23 +24,16 @@ import org.apache.ibatis.parsing.XNode; import org.apache.ibatis.scripting.defaults.RawLanguageDriver; import org.apache.ibatis.session.Configuration; -import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; -import static org.hamcrest.core.Is.is; -import static org.hamcrest.core.IsInstanceOf.instanceOf; -import static org.hamcrest.core.IsSame.sameInstance; -import static org.junit.Assert.assertThat; +import static com.googlecode.catchexception.apis.BDDCatchException.*; +import static org.assertj.core.api.BDDAssertions.then; /** * @author Kazuki Shimizu */ public class LanguageDriverRegistryTest { - @Rule - public ExpectedException expectedException = ExpectedException.none(); - private LanguageDriverRegistry registry = new LanguageDriverRegistry(); @Test @@ -46,7 +41,7 @@ public void registerByType() { registry.register(RawLanguageDriver.class); LanguageDriver driver = registry.getDriver(RawLanguageDriver.class); - assertThat(driver, instanceOf(RawLanguageDriver.class)); + assertThat(driver).isInstanceOf(RawLanguageDriver.class); } @Test @@ -56,21 +51,21 @@ public void registerByTypeSameType() { registry.register(RawLanguageDriver.class); - assertThat(driver, sameInstance(registry.getDriver(RawLanguageDriver.class))); + assertThat(driver).isSameAs(registry.getDriver(RawLanguageDriver.class)); } @Test public void registerByTypeNull() { - expectedException.expect(IllegalArgumentException.class); - expectedException.expectMessage("null is not a valid Language Driver"); - registry.register((Class) null); + when(registry).register((Class) null); + then(caughtException()).isInstanceOf(IllegalArgumentException.class) + .hasMessage("null is not a valid Language Driver"); } @Test public void registerByTypeDoesNotCreateNewInstance() { - expectedException.expect(ScriptingException.class); - expectedException.expectMessage("Failed to load language driver for org.apache.ibatis.scripting.LanguageDriverRegistryTest$PrivateLanguageDriver"); - registry.register(PrivateLanguageDriver.class); + when(registry).register(PrivateLanguageDriver.class); + then(caughtException()).isInstanceOf(ScriptingException.class) + .hasMessage("Failed to load language driver for org.apache.ibatis.scripting.LanguageDriverRegistryTest$PrivateLanguageDriver"); } @Test @@ -78,7 +73,7 @@ public void registerByInstance() { registry.register(new PrivateLanguageDriver()); LanguageDriver driver = registry.getDriver(PrivateLanguageDriver.class); - assertThat(driver, instanceOf(PrivateLanguageDriver.class)); + assertThat(driver).isInstanceOf(PrivateLanguageDriver.class); } @Test @@ -88,21 +83,21 @@ public void registerByInstanceSameType() { registry.register(new PrivateLanguageDriver()); - assertThat(driver, sameInstance(registry.getDriver(PrivateLanguageDriver.class))); + assertThat(driver).isSameAs(registry.getDriver(PrivateLanguageDriver.class)); } @Test public void registerByInstanceNull() { - expectedException.expect(IllegalArgumentException.class); - expectedException.expectMessage("null is not a valid Language Driver"); - registry.register((LanguageDriver) null); + when(registry).register((LanguageDriver) null); + then(caughtException()).isInstanceOf(IllegalArgumentException.class) + .hasMessage("null is not a valid Language Driver"); } @Test public void setDefaultDriverClass() { registry.setDefaultDriverClass(RawLanguageDriver.class); - assertThat(registry.getDefaultDriverClass() == RawLanguageDriver.class, is(true)); - assertThat(registry.getDefaultDriver(), instanceOf(RawLanguageDriver.class)); + assertThat(registry.getDefaultDriverClass() == RawLanguageDriver.class).isTrue(); + assertThat(registry.getDefaultDriver()).isInstanceOf(RawLanguageDriver.class); } static private class PrivateLanguageDriver implements LanguageDriver { diff --git a/src/test/java/org/apache/ibatis/scripting/defaults/DefaultParameterHandlerTest.java b/src/test/java/org/apache/ibatis/scripting/defaults/DefaultParameterHandlerTest.java index 3d8ecfc5378..ebcfc9d6aa2 100644 --- a/src/test/java/org/apache/ibatis/scripting/defaults/DefaultParameterHandlerTest.java +++ b/src/test/java/org/apache/ibatis/scripting/defaults/DefaultParameterHandlerTest.java @@ -1,5 +1,5 @@ /** - * Copyright 2009-2016 the original author or authors. + * Copyright 2009-2017 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. @@ -34,7 +34,6 @@ import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.anyInt; -import static org.mockito.ArgumentMatchers.anyObject; import static org.mockito.Mockito.doThrow; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; diff --git a/src/test/java/org/apache/ibatis/session/AutoMappingUnknownColumnBehaviorTest.java b/src/test/java/org/apache/ibatis/session/AutoMappingUnknownColumnBehaviorTest.java index d7d68f84e1d..8a7e349add5 100644 --- a/src/test/java/org/apache/ibatis/session/AutoMappingUnknownColumnBehaviorTest.java +++ b/src/test/java/org/apache/ibatis/session/AutoMappingUnknownColumnBehaviorTest.java @@ -30,10 +30,7 @@ import javax.sql.DataSource; import java.util.concurrent.atomic.AtomicInteger; -import static org.hamcrest.CoreMatchers.instanceOf; -import static org.hamcrest.core.Is.is; -import static org.hamcrest.core.IsNull.nullValue; -import static org.junit.Assert.assertThat; +import static org.assertj.core.api.Assertions.assertThat; /** * Tests for specify the behavior when detects an unknown column (or unknown property type) of automatic mapping target. @@ -110,8 +107,8 @@ public void none() { try { Mapper mapper = session.getMapper(Mapper.class); Author author = mapper.selectAuthor(101); - assertThat(author.getId(), is(101)); - assertThat(author.getUsername(), nullValue()); + assertThat(author.getId()).isEqualTo(101); + assertThat(author.getUsername()).isNull(); } finally { session.close(); } @@ -127,9 +124,9 @@ public void warningCauseByUnknownPropertyType() { try { Mapper mapper = session.getMapper(Mapper.class); SimpleAuthor author = mapper.selectSimpleAuthor(101); - assertThat(author.getId(), nullValue()); - assertThat(author.getUsername(), is("jim")); - assertThat(LastEventSavedAppender.event.getMessage().toString(), is("Unknown column is detected on 'org.apache.ibatis.session.AutoMappingUnknownColumnBehaviorTest$Mapper.selectSimpleAuthor' auto-mapping. Mapping parameters are [columnName=ID,propertyName=id,propertyType=java.util.concurrent.atomic.AtomicInteger]")); + assertThat(author.getId()).isNull(); + assertThat(author.getUsername()).isEqualTo("jim"); + assertThat(LastEventSavedAppender.event.getMessage().toString()).isEqualTo("Unknown column is detected on 'org.apache.ibatis.session.AutoMappingUnknownColumnBehaviorTest$Mapper.selectSimpleAuthor' auto-mapping. Mapping parameters are [columnName=ID,propertyName=id,propertyType=java.util.concurrent.atomic.AtomicInteger]"); } finally { session.close(); @@ -147,8 +144,8 @@ public void failingCauseByUnknownColumn() { Mapper mapper = session.getMapper(Mapper.class); mapper.selectAuthor(101); } catch (PersistenceException e) { - assertThat(e.getCause(), instanceOf(SqlSessionException.class)); - assertThat(e.getCause().getMessage(), is("Unknown column is detected on 'org.apache.ibatis.session.AutoMappingUnknownColumnBehaviorTest$Mapper.selectAuthor' auto-mapping. Mapping parameters are [columnName=USERNAMEEEE,propertyName=USERNAMEEEE,propertyType=null]")); + assertThat(e.getCause()).isInstanceOf(SqlSessionException.class); + assertThat(e.getCause().getMessage()).isEqualTo("Unknown column is detected on 'org.apache.ibatis.session.AutoMappingUnknownColumnBehaviorTest$Mapper.selectAuthor' auto-mapping. Mapping parameters are [columnName=USERNAMEEEE,propertyName=USERNAMEEEE,propertyType=null]"); } finally { session.close(); } diff --git a/src/test/java/org/apache/ibatis/submitted/cache/CacheTest.java b/src/test/java/org/apache/ibatis/submitted/cache/CacheTest.java index 50310f37721..3b4b4191a0f 100644 --- a/src/test/java/org/apache/ibatis/submitted/cache/CacheTest.java +++ b/src/test/java/org/apache/ibatis/submitted/cache/CacheTest.java @@ -1,5 +1,5 @@ /** - * Copyright 2009-2016 the original author or authors. + * Copyright 2009-2017 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. @@ -32,18 +32,16 @@ import org.apache.ibatis.session.SqlSessionFactoryBuilder; import org.junit.Assert; import org.junit.Before; -import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; + +import static com.googlecode.catchexception.apis.BDDCatchException.*; +import static org.assertj.core.api.BDDAssertions.then; // issue #524 public class CacheTest { private static SqlSessionFactory sqlSessionFactory; - @Rule - public ExpectedException expectedException = ExpectedException.none(); - @Before public void setUp() throws Exception { // create a SqlSessionFactory @@ -349,28 +347,25 @@ public void shouldApplyCustomCacheProperties() { @Test public void shouldErrorUnsupportedProperties() { - expectedException.expect(CacheException.class); - expectedException.expectMessage("Unsupported property type for cache: 'date' of type class java.util.Date"); - - sqlSessionFactory.getConfiguration().addMapper(CustomCacheUnsupportedPropertyMapper.class); + when(sqlSessionFactory.getConfiguration()).addMapper(CustomCacheUnsupportedPropertyMapper.class); + then(caughtException()).isInstanceOf(CacheException.class) + .hasMessage("Unsupported property type for cache: 'date' of type class java.util.Date"); } @Test public void shouldErrorInvalidCacheNamespaceRefAttributesSpecifyBoth() { - expectedException.expect(BuilderException.class); - expectedException.expectMessage("Cannot use both value() and name() attribute in the @CacheNamespaceRef"); - - sqlSessionFactory.getConfiguration().getMapperRegistry() - .addMapper(InvalidCacheNamespaceRefBothMapper.class); + when(sqlSessionFactory.getConfiguration().getMapperRegistry()) + .addMapper(InvalidCacheNamespaceRefBothMapper.class); + then(caughtException()).isInstanceOf(BuilderException.class) + .hasMessage("Cannot use both value() and name() attribute in the @CacheNamespaceRef"); } @Test public void shouldErrorInvalidCacheNamespaceRefAttributesIsEmpty() { - expectedException.expect(BuilderException.class); - expectedException.expectMessage("Should be specified either value() or name() attribute in the @CacheNamespaceRef"); - - sqlSessionFactory.getConfiguration().getMapperRegistry() - .addMapper(InvalidCacheNamespaceRefEmptyMapper.class); + when(sqlSessionFactory.getConfiguration().getMapperRegistry()) + .addMapper(InvalidCacheNamespaceRefEmptyMapper.class); + then(caughtException()).isInstanceOf(BuilderException.class) + .hasMessage("Should be specified either value() or name() attribute in the @CacheNamespaceRef"); } private CustomCache unwrap(Cache cache){ diff --git a/src/test/java/org/apache/ibatis/submitted/call_setters_on_nulls_again/MyBatisTest.java b/src/test/java/org/apache/ibatis/submitted/call_setters_on_nulls_again/MyBatisTest.java index 39cf46ddc52..e55de6005cc 100644 --- a/src/test/java/org/apache/ibatis/submitted/call_setters_on_nulls_again/MyBatisTest.java +++ b/src/test/java/org/apache/ibatis/submitted/call_setters_on_nulls_again/MyBatisTest.java @@ -43,8 +43,6 @@ public void test() { try { ParentBean parentBean = session.selectOne("test"); Assert.assertEquals("p1", parentBean.getName()); -// Assert.assertThat(parentBean.toString(), CoreMatchers.is("ParentBean [name=p1, client=ChildBean [name=null, child=ChildBean [name=null, child=null, beans=null], beans=null]]")); - } finally { session.close(); } diff --git a/src/test/java/org/apache/ibatis/submitted/enumtypehandler_on_annotation/EnumTypeHandlerUsingAnnotationTest.java b/src/test/java/org/apache/ibatis/submitted/enumtypehandler_on_annotation/EnumTypeHandlerUsingAnnotationTest.java index 92cf848fdcd..444d06d15a3 100644 --- a/src/test/java/org/apache/ibatis/submitted/enumtypehandler_on_annotation/EnumTypeHandlerUsingAnnotationTest.java +++ b/src/test/java/org/apache/ibatis/submitted/enumtypehandler_on_annotation/EnumTypeHandlerUsingAnnotationTest.java @@ -29,8 +29,7 @@ import java.sql.Connection; import java.sql.DriverManager; -import static org.junit.Assert.*; -import static org.hamcrest.core.Is.*; +import static org.assertj.core.api.Assertions.assertThat; /** * Tests for type handler of enum using annotations. @@ -91,17 +90,17 @@ public void testForArg() { PersonMapper personMapper = sqlSession.getMapper(PersonMapper.class); { Person person = personMapper.findOneUsingConstructor(1); - assertThat(person.getId(), is(1)); - assertThat(person.getFirstName(), is("John")); - assertThat(person.getLastName(), is("Smith")); - assertThat(person.getPersonType(), is(Person.PersonType.PERSON)); // important + assertThat(person.getId()).isEqualTo(1); + assertThat(person.getFirstName()).isEqualTo("John"); + assertThat(person.getLastName()).isEqualTo("Smith"); + assertThat(person.getPersonType()).isEqualTo(Person.PersonType.PERSON); // important } { Person employee = personMapper.findOneUsingConstructor(2); - assertThat(employee.getId(), is(2)); - assertThat(employee.getFirstName(), is("Mike")); - assertThat(employee.getLastName(), is("Jordan")); - assertThat(employee.getPersonType(), is(Person.PersonType.EMPLOYEE)); // important + assertThat(employee.getId()).isEqualTo(2); + assertThat(employee.getFirstName()).isEqualTo("Mike"); + assertThat(employee.getLastName()).isEqualTo("Jordan"); + assertThat(employee.getPersonType()).isEqualTo(Person.PersonType.EMPLOYEE); // important } } @@ -110,17 +109,17 @@ public void testForResult() { PersonMapper personMapper = sqlSession.getMapper(PersonMapper.class); { Person person = personMapper.findOneUsingSetter(1); - assertThat(person.getId(), is(1)); - assertThat(person.getFirstName(), is("John")); - assertThat(person.getLastName(), is("Smith")); - assertThat(person.getPersonType(), is(Person.PersonType.PERSON)); // important + assertThat(person.getId()).isEqualTo(1); + assertThat(person.getFirstName()).isEqualTo("John"); + assertThat(person.getLastName()).isEqualTo("Smith"); + assertThat(person.getPersonType()).isEqualTo(Person.PersonType.PERSON); // important } { Person employee = personMapper.findOneUsingSetter(2); - assertThat(employee.getId(), is(2)); - assertThat(employee.getFirstName(), is("Mike")); - assertThat(employee.getLastName(), is("Jordan")); - assertThat(employee.getPersonType(), is(Person.PersonType.EMPLOYEE)); // important + assertThat(employee.getId()).isEqualTo(2); + assertThat(employee.getFirstName()).isEqualTo("Mike"); + assertThat(employee.getLastName()).isEqualTo("Jordan"); + assertThat(employee.getPersonType()).isEqualTo(Person.PersonType.EMPLOYEE); // important } } @@ -129,19 +128,19 @@ public void testForTypeDiscriminator() { PersonMapper personMapper = sqlSession.getMapper(PersonMapper.class); { Person person = personMapper.findOneUsingTypeDiscriminator(1); - assertTrue(person.getClass() == Person.class); // important - assertThat(person.getId(), is(1)); - assertThat(person.getFirstName(), is("John")); - assertThat(person.getLastName(), is("Smith")); - assertThat(person.getPersonType(), is(Person.PersonType.PERSON)); + assertThat(person.getClass()).isEqualTo(Person.class); // important + assertThat(person.getId()).isEqualTo(1); + assertThat(person.getFirstName()).isEqualTo("John"); + assertThat(person.getLastName()).isEqualTo("Smith"); + assertThat(person.getPersonType()).isEqualTo(Person.PersonType.PERSON); } { Person employee = personMapper.findOneUsingTypeDiscriminator(2); - assertTrue(employee.getClass() == Employee.class); // important - assertThat(employee.getId(), is(2)); - assertThat(employee.getFirstName(), is("Mike")); - assertThat(employee.getLastName(), is("Jordan")); - assertThat(employee.getPersonType(), is(Person.PersonType.EMPLOYEE)); + assertThat(employee.getClass()).isEqualTo(Employee.class); // important + assertThat(employee.getId()).isEqualTo(2); + assertThat(employee.getFirstName()).isEqualTo("Mike"); + assertThat(employee.getLastName()).isEqualTo("Jordan"); + assertThat(employee.getPersonType()).isEqualTo(Person.PersonType.EMPLOYEE); } } diff --git a/src/test/java/org/apache/ibatis/submitted/foreach/ForEachTest.java b/src/test/java/org/apache/ibatis/submitted/foreach/ForEachTest.java index 1a854833572..0f1a4e3f27b 100644 --- a/src/test/java/org/apache/ibatis/submitted/foreach/ForEachTest.java +++ b/src/test/java/org/apache/ibatis/submitted/foreach/ForEachTest.java @@ -1,5 +1,5 @@ /** - * Copyright 2009-2015 the original author or authors. + * Copyright 2009-2017 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. @@ -29,17 +29,15 @@ import org.apache.ibatis.session.SqlSessionFactoryBuilder; import org.junit.Assert; import org.junit.BeforeClass; -import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; + +import static com.googlecode.catchexception.apis.BDDCatchException.*; +import static org.assertj.core.api.BDDAssertions.then; public class ForEachTest { private static SqlSessionFactory sqlSessionFactory; - @Rule - public ExpectedException ex = ExpectedException.none(); - @BeforeClass public static void setUp() throws Exception { // create a SqlSessionFactory @@ -133,13 +131,12 @@ public void nullItemInContext() { @Test public void shouldReportMissingPropertyName() { - ex.expect(PersistenceException.class); - ex.expectMessage("There is no getter for property named 'idd' in 'class org.apache.ibatis.submitted.foreach.User'"); - SqlSession sqlSession = sqlSessionFactory.openSession(); try { Mapper mapper = sqlSession.getMapper(Mapper.class); - mapper.typoInItemProperty(Arrays.asList(new User())); + when(mapper).typoInItemProperty(Arrays.asList(new User())); + then(caughtException()).isInstanceOf(PersistenceException.class) + .hasMessageContaining("There is no getter for property named 'idd' in 'class org.apache.ibatis.submitted.foreach.User'"); } finally { sqlSession.close(); } diff --git a/src/test/java/org/apache/ibatis/submitted/global_variables_defaults/AnnotationMapperTest.java b/src/test/java/org/apache/ibatis/submitted/global_variables_defaults/AnnotationMapperTest.java index d70660b7b27..9e1cc59663a 100644 --- a/src/test/java/org/apache/ibatis/submitted/global_variables_defaults/AnnotationMapperTest.java +++ b/src/test/java/org/apache/ibatis/submitted/global_variables_defaults/AnnotationMapperTest.java @@ -1,5 +1,5 @@ /** - * Copyright 2009-2016 the original author or authors. + * Copyright 2009-2017 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. @@ -24,8 +24,7 @@ import org.apache.ibatis.session.SqlSession; import org.apache.ibatis.session.SqlSessionFactory; import org.apache.ibatis.session.SqlSessionFactoryBuilder; -import org.hamcrest.core.Is; -import org.junit.Assert; +import org.assertj.core.api.Assertions; import org.junit.Test; import java.io.IOException; @@ -46,13 +45,13 @@ public void applyDefaultValueOnAnnotationMapper() throws IOException { configuration.addMapper(AnnotationMapper.class); SupportClasses.CustomCache cache = SupportClasses.Utils.unwrap(configuration.getCache(AnnotationMapper.class.getName())); - Assert.assertThat(cache.getName(), Is.is("default")); + Assertions.assertThat(cache.getName()).isEqualTo("default"); SqlSession sqlSession = factory.openSession(); try { AnnotationMapper mapper = sqlSession.getMapper(AnnotationMapper.class); - Assert.assertThat(mapper.ping(), Is.is("Hello")); + Assertions.assertThat(mapper.ping()).isEqualTo("Hello"); } finally { sqlSession.close(); @@ -74,13 +73,13 @@ public void applyPropertyValueOnAnnotationMapper() throws IOException { configuration.addMapper(AnnotationMapper.class); SupportClasses.CustomCache cache = SupportClasses.Utils.unwrap(configuration.getCache(AnnotationMapper.class.getName())); - Assert.assertThat(cache.getName(), Is.is("custom")); + Assertions.assertThat(cache.getName()).isEqualTo("custom"); SqlSession sqlSession = factory.openSession(); try { AnnotationMapper mapper = sqlSession.getMapper(AnnotationMapper.class); - Assert.assertThat(mapper.ping(), Is.is("Hi")); + Assertions.assertThat(mapper.ping()).isEqualTo("Hi"); } finally { sqlSession.close(); diff --git a/src/test/java/org/apache/ibatis/submitted/global_variables_defaults/ConfigurationTest.java b/src/test/java/org/apache/ibatis/submitted/global_variables_defaults/ConfigurationTest.java index 812602d5c92..035efef8967 100644 --- a/src/test/java/org/apache/ibatis/submitted/global_variables_defaults/ConfigurationTest.java +++ b/src/test/java/org/apache/ibatis/submitted/global_variables_defaults/ConfigurationTest.java @@ -1,5 +1,5 @@ /** - * Copyright 2009-2016 the original author or authors. + * Copyright 2009-2017 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. @@ -22,9 +22,7 @@ import org.apache.ibatis.session.SqlSessionFactory; import org.apache.ibatis.session.SqlSessionFactoryBuilder; import org.apache.ibatis.type.JdbcType; -import org.hamcrest.core.Is; -import org.hamcrest.core.IsNull; -import org.junit.Assert; +import org.assertj.core.api.Assertions; import org.junit.Test; import java.io.IOException; @@ -43,12 +41,12 @@ public void applyDefaultValueOnXmlConfiguration() throws IOException { SqlSessionFactory factory = new SqlSessionFactoryBuilder().build(reader, props); Configuration configuration = factory.getConfiguration(); - Assert.assertThat(configuration.getJdbcTypeForNull(), Is.is(JdbcType.NULL)); - Assert.assertThat(((UnpooledDataSource) configuration.getEnvironment().getDataSource()).getUrl(), - Is.is("jdbc:hsqldb:mem:global_variables_defaults")); - Assert.assertThat(configuration.getDatabaseId(), Is.is("hsql")); - Assert.assertThat(((SupportClasses.CustomObjectFactory) configuration.getObjectFactory()).getProperties().getProperty("name"), - Is.is("default")); + Assertions.assertThat(configuration.getJdbcTypeForNull()).isEqualTo(JdbcType.NULL); + Assertions.assertThat(((UnpooledDataSource) configuration.getEnvironment().getDataSource()).getUrl()) + .isEqualTo("jdbc:hsqldb:mem:global_variables_defaults"); + Assertions.assertThat(configuration.getDatabaseId()).isEqualTo("hsql"); + Assertions.assertThat(((SupportClasses.CustomObjectFactory) configuration.getObjectFactory()).getProperties().getProperty("name")) + .isEqualTo("default"); } @@ -66,12 +64,12 @@ public void applyPropertyValueOnXmlConfiguration() throws IOException { SqlSessionFactory factory = new SqlSessionFactoryBuilder().build(reader, props); Configuration configuration = factory.getConfiguration(); - Assert.assertThat(configuration.getJdbcTypeForNull(), Is.is(JdbcType.CHAR)); - Assert.assertThat(((UnpooledDataSource) configuration.getEnvironment().getDataSource()).getUrl(), - Is.is("jdbc:hsqldb:mem:global_variables_defaults_custom")); - Assert.assertThat(configuration.getDatabaseId(), IsNull.nullValue()); - Assert.assertThat(((SupportClasses.CustomObjectFactory) configuration.getObjectFactory()).getProperties().getProperty("name"), - Is.is("custom")); + Assertions.assertThat(configuration.getJdbcTypeForNull()).isEqualTo(JdbcType.CHAR); + Assertions.assertThat(((UnpooledDataSource) configuration.getEnvironment().getDataSource()).getUrl()) + .isEqualTo("jdbc:hsqldb:mem:global_variables_defaults_custom"); + Assertions.assertThat(configuration.getDatabaseId()).isNull(); + Assertions.assertThat(((SupportClasses.CustomObjectFactory) configuration.getObjectFactory()).getProperties().getProperty("name")) + .isEqualTo("custom"); } diff --git a/src/test/java/org/apache/ibatis/submitted/global_variables_defaults/CustomizationTest.java b/src/test/java/org/apache/ibatis/submitted/global_variables_defaults/CustomizationTest.java index 9f11e6315df..efd67b57973 100644 --- a/src/test/java/org/apache/ibatis/submitted/global_variables_defaults/CustomizationTest.java +++ b/src/test/java/org/apache/ibatis/submitted/global_variables_defaults/CustomizationTest.java @@ -1,5 +1,5 @@ /** - * Copyright 2009-2016 the original author or authors. + * Copyright 2009-2017 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. @@ -27,9 +27,7 @@ import org.apache.ibatis.session.SqlSessionFactory; import org.apache.ibatis.session.SqlSessionFactoryBuilder; import org.apache.ibatis.type.JdbcType; -import org.hamcrest.core.Is; -import org.hamcrest.core.IsNull; -import org.junit.Assert; +import org.assertj.core.api.Assertions; import org.junit.Test; import java.io.IOException; @@ -52,18 +50,18 @@ public void applyDefaultValueWhenCustomizeDefaultValueSeparator() throws IOExcep SupportClasses.CustomCache cache = SupportClasses.Utils.unwrap(configuration.getCache(CustomDefaultValueSeparatorMapper.class.getName())); - Assert.assertThat(configuration.getJdbcTypeForNull(), Is.is(JdbcType.NULL)); - Assert.assertThat(((UnpooledDataSource) configuration.getEnvironment().getDataSource()).getUrl(), - Is.is("jdbc:hsqldb:mem:global_variables_defaults")); - Assert.assertThat(configuration.getDatabaseId(), Is.is("hsql")); - Assert.assertThat(((SupportClasses.CustomObjectFactory) configuration.getObjectFactory()).getProperties().getProperty("name"), - Is.is("default")); - Assert.assertThat(cache.getName(), Is.is("default")); + Assertions.assertThat(configuration.getJdbcTypeForNull()).isEqualTo(JdbcType.NULL); + Assertions.assertThat(((UnpooledDataSource) configuration.getEnvironment().getDataSource()).getUrl()) + .isEqualTo("jdbc:hsqldb:mem:global_variables_defaults"); + Assertions.assertThat(configuration.getDatabaseId()).isEqualTo("hsql"); + Assertions.assertThat(((SupportClasses.CustomObjectFactory) configuration.getObjectFactory()).getProperties().getProperty("name")) + .isEqualTo("default"); + Assertions.assertThat(cache.getName()).isEqualTo("default"); SqlSession sqlSession = factory.openSession(); try { CustomDefaultValueSeparatorMapper mapper = sqlSession.getMapper(CustomDefaultValueSeparatorMapper.class); - Assert.assertThat(mapper.selectValue(null), Is.is("default")); + Assertions.assertThat(mapper.selectValue(null)).isEqualTo("default"); } finally { sqlSession.close(); } @@ -89,18 +87,18 @@ public void applyPropertyValueWhenCustomizeDefaultValueSeparator() throws IOExce SupportClasses.CustomCache cache = SupportClasses.Utils.unwrap(configuration.getCache(CustomDefaultValueSeparatorMapper.class.getName())); - Assert.assertThat(configuration.getJdbcTypeForNull(), Is.is(JdbcType.CHAR)); - Assert.assertThat(((UnpooledDataSource) configuration.getEnvironment().getDataSource()).getUrl(), - Is.is("jdbc:hsqldb:mem:global_variables_defaults_custom")); - Assert.assertThat(configuration.getDatabaseId(), IsNull.nullValue()); - Assert.assertThat(((SupportClasses.CustomObjectFactory) configuration.getObjectFactory()).getProperties().getProperty("name"), - Is.is("customObjectFactory")); - Assert.assertThat(cache.getName(), Is.is("customCache")); + Assertions.assertThat(configuration.getJdbcTypeForNull()).isEqualTo(JdbcType.CHAR); + Assertions.assertThat(((UnpooledDataSource) configuration.getEnvironment().getDataSource()).getUrl()) + .isEqualTo("jdbc:hsqldb:mem:global_variables_defaults_custom"); + Assertions.assertThat(configuration.getDatabaseId()).isNull(); + Assertions.assertThat(((SupportClasses.CustomObjectFactory) configuration.getObjectFactory()).getProperties().getProperty("name")) + .isEqualTo("customObjectFactory"); + Assertions.assertThat(cache.getName()).isEqualTo("customCache"); SqlSession sqlSession = factory.openSession(); try { CustomDefaultValueSeparatorMapper mapper = sqlSession.getMapper(CustomDefaultValueSeparatorMapper.class); - Assert.assertThat(mapper.selectValue("3333"), Is.is("3333")); + Assertions.assertThat(mapper.selectValue("3333")).isEqualTo("3333"); } finally { sqlSession.close(); } diff --git a/src/test/java/org/apache/ibatis/submitted/global_variables_defaults/XmlMapperTest.java b/src/test/java/org/apache/ibatis/submitted/global_variables_defaults/XmlMapperTest.java index 52b79f5a463..e6f709dd3df 100644 --- a/src/test/java/org/apache/ibatis/submitted/global_variables_defaults/XmlMapperTest.java +++ b/src/test/java/org/apache/ibatis/submitted/global_variables_defaults/XmlMapperTest.java @@ -1,5 +1,5 @@ /** - * Copyright 2009-2016 the original author or authors. + * Copyright 2009-2017 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. @@ -21,8 +21,7 @@ import org.apache.ibatis.session.SqlSession; import org.apache.ibatis.session.SqlSessionFactory; import org.apache.ibatis.session.SqlSessionFactoryBuilder; -import org.hamcrest.core.Is; -import org.junit.Assert; +import org.assertj.core.api.Assertions; import org.junit.Test; import java.io.IOException; @@ -43,15 +42,15 @@ public void applyDefaultValueOnXmlMapper() throws IOException { configuration.addMapper(XmlMapper.class); SupportClasses.CustomCache cache = SupportClasses.Utils.unwrap(configuration.getCache(XmlMapper.class.getName())); - Assert.assertThat(cache.getName(), Is.is("default")); + Assertions.assertThat(cache.getName()).isEqualTo("default"); SqlSession sqlSession = factory.openSession(); try { XmlMapper mapper = sqlSession.getMapper(XmlMapper.class); - Assert.assertThat(mapper.ping(), Is.is("Hello")); - Assert.assertThat(mapper.selectOne(), Is.is("1")); - Assert.assertThat(mapper.selectFromVariable(), Is.is("9999")); + Assertions.assertThat(mapper.ping()).isEqualTo("Hello"); + Assertions.assertThat(mapper.selectOne()).isEqualTo("1"); + Assertions.assertThat(mapper.selectFromVariable()).isEqualTo("9999"); } finally { sqlSession.close(); @@ -74,15 +73,15 @@ public void applyPropertyValueOnXmlMapper() throws IOException { configuration.addMapper(XmlMapper.class); SupportClasses.CustomCache cache = SupportClasses.Utils.unwrap(configuration.getCache(XmlMapper.class.getName())); - Assert.assertThat(cache.getName(), Is.is("custom")); + Assertions.assertThat(cache.getName()).isEqualTo("custom"); SqlSession sqlSession = factory.openSession(); try { XmlMapper mapper = sqlSession.getMapper(XmlMapper.class); - Assert.assertThat(mapper.ping(), Is.is("Hi")); - Assert.assertThat(mapper.selectOne(), Is.is("1")); - Assert.assertThat(mapper.selectFromVariable(), Is.is("5555")); + Assertions.assertThat(mapper.ping()).isEqualTo("Hi"); + Assertions.assertThat(mapper.selectOne()).isEqualTo("1"); + Assertions.assertThat(mapper.selectFromVariable()).isEqualTo("5555"); } finally { sqlSession.close(); diff --git a/src/test/java/org/apache/ibatis/submitted/keygen/Jdbc3KeyGeneratorTest.java b/src/test/java/org/apache/ibatis/submitted/keygen/Jdbc3KeyGeneratorTest.java index 8e809a391ad..8c94a0f1e5c 100644 --- a/src/test/java/org/apache/ibatis/submitted/keygen/Jdbc3KeyGeneratorTest.java +++ b/src/test/java/org/apache/ibatis/submitted/keygen/Jdbc3KeyGeneratorTest.java @@ -1,5 +1,5 @@ /** - * Copyright 2009-2016 the original author or authors. + * Copyright 2009-2017 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. @@ -29,11 +29,10 @@ import org.apache.ibatis.session.SqlSessionFactory; import org.apache.ibatis.session.SqlSessionFactoryBuilder; import org.junit.BeforeClass; -import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; -import static org.hamcrest.CoreMatchers.*; +import static com.googlecode.catchexception.apis.BDDCatchException.*; +import static org.assertj.core.api.BDDAssertions.then; /** * @author liuzh @@ -42,9 +41,6 @@ public class Jdbc3KeyGeneratorTest { private static SqlSessionFactory sqlSessionFactory; - @Rule - public ExpectedException expectedException = ExpectedException.none(); - @BeforeClass public static void setUp() throws Exception { // create an SqlSessionFactory @@ -88,10 +84,9 @@ public void shouldErrorUndefineProperty() { try { CountryMapper mapper = sqlSession.getMapper(CountryMapper.class); - expectedException.expect(PersistenceException.class); - expectedException.expectMessage(containsString("### Error updating database. Cause: org.apache.ibatis.executor.ExecutorException: Error getting generated key or setting result to parameter object. Cause: org.apache.ibatis.executor.ExecutorException: No setter found for the keyProperty 'country_id' in org.apache.ibatis.submitted.keygen.Country.")); - - mapper.insertUndefineKeyProperty(new Country("China", "CN")); + when(mapper).insertUndefineKeyProperty(new Country("China", "CN")); + then(caughtException()).isInstanceOf(PersistenceException.class).hasMessageContaining( + "### Error updating database. Cause: org.apache.ibatis.executor.ExecutorException: Error getting generated key or setting result to parameter object. Cause: org.apache.ibatis.executor.ExecutorException: No setter found for the keyProperty 'country_id' in org.apache.ibatis.submitted.keygen.Country."); } finally { sqlSession.rollback(); sqlSession.close(); diff --git a/src/test/java/org/apache/ibatis/submitted/lazy_deserialize/LazyDeserializeTest.java b/src/test/java/org/apache/ibatis/submitted/lazy_deserialize/LazyDeserializeTest.java index 4a14779eb43..8cb9837747a 100644 --- a/src/test/java/org/apache/ibatis/submitted/lazy_deserialize/LazyDeserializeTest.java +++ b/src/test/java/org/apache/ibatis/submitted/lazy_deserialize/LazyDeserializeTest.java @@ -15,7 +15,6 @@ */ package org.apache.ibatis.submitted.lazy_deserialize; -import static org.hamcrest.core.Is.*; import static org.junit.Assert.*; import java.io.ByteArrayInputStream; @@ -35,9 +34,7 @@ import org.apache.ibatis.session.SqlSessionFactory; import org.apache.ibatis.session.SqlSessionFactoryBuilder; import org.junit.Before; -import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; /** * @@ -46,9 +43,6 @@ */ public final class LazyDeserializeTest { - @Rule - public ExpectedException expectedException = ExpectedException.none(); - private static final int FOO_ID = 1; private static final int BAR_ID = 10; private static SqlSessionFactory factory; @@ -108,17 +102,17 @@ public void testLoadLazyDeserialize() throws Exception { @Test public void testLoadLazyDeserializeWithoutConfigurationFactory() throws Exception { - expectedException.expect(ExecutorException.class); - expectedException - .expectMessage(is("Cannot get Configuration as configuration factory was not set.")); - final SqlSession session = factory.openSession(); try { final Mapper mapper = session.getMapper(Mapper.class); final LazyObjectFoo foo = mapper.loadFoo(FOO_ID); final byte[] serializedFoo = this.serializeFoo(foo); final LazyObjectFoo deserializedFoo = this.deserializeFoo(serializedFoo); - deserializedFoo.getLazyObjectBar(); + try { + deserializedFoo.getLazyObjectBar(); + } catch (ExecutorException e) { + e.getMessage().contains("Cannot get Configuration as configuration factory was not set."); + } } finally { session.close(); } diff --git a/src/test/java/org/apache/ibatis/submitted/mapper_extend/MapperExtendTest.java b/src/test/java/org/apache/ibatis/submitted/mapper_extend/MapperExtendTest.java index 2fe549cd0ba..05e98c02522 100644 --- a/src/test/java/org/apache/ibatis/submitted/mapper_extend/MapperExtendTest.java +++ b/src/test/java/org/apache/ibatis/submitted/mapper_extend/MapperExtendTest.java @@ -15,8 +15,6 @@ */ package org.apache.ibatis.submitted.mapper_extend; -import static org.hamcrest.CoreMatchers.*; - import java.io.Reader; import java.sql.Connection; @@ -28,14 +26,12 @@ import org.apache.ibatis.session.SqlSessionFactoryBuilder; import org.junit.Assert; import org.junit.BeforeClass; -import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; -public class MapperExtendTest { +import static com.googlecode.catchexception.apis.BDDCatchException.*; +import static org.assertj.core.api.BDDAssertions.then; - @Rule - public ExpectedException expectedException = ExpectedException.none(); +public class MapperExtendTest { private static SqlSessionFactory sqlSessionFactory; @@ -120,15 +116,13 @@ public void shouldFindStatementInSubInterfaceOfDeclaringClass() { @Test public void shouldThrowExceptionIfNoMatchingStatementFound() { - expectedException.expect(BindingException.class); - expectedException.expectMessage(is("Invalid bound statement (not found): " - + Mapper.class.getName() + ".noMappedStatement")); - SqlSession sqlSession = sqlSessionFactory.openSession(); try { Mapper mapper = sqlSession.getMapper(Mapper.class); - User user = mapper.noMappedStatement(); - Assert.assertNotNull(user); + when(mapper).noMappedStatement(); + then(caughtException()).isInstanceOf(BindingException.class) + .hasMessage("Invalid bound statement (not found): " + + Mapper.class.getName() + ".noMappedStatement"); } finally { sqlSession.close(); } diff --git a/src/test/java/org/apache/ibatis/submitted/named_constructor_args/InvalidNamedConstructorArgsTest.java b/src/test/java/org/apache/ibatis/submitted/named_constructor_args/InvalidNamedConstructorArgsTest.java index af4d9b5683d..be155399aef 100644 --- a/src/test/java/org/apache/ibatis/submitted/named_constructor_args/InvalidNamedConstructorArgsTest.java +++ b/src/test/java/org/apache/ibatis/submitted/named_constructor_args/InvalidNamedConstructorArgsTest.java @@ -15,8 +15,6 @@ */ package org.apache.ibatis.submitted.named_constructor_args; -import static org.hamcrest.CoreMatchers.*; - import java.io.Reader; import java.sql.Connection; @@ -31,13 +29,12 @@ import org.apache.ibatis.session.SqlSessionFactory; import org.apache.ibatis.session.SqlSessionFactoryBuilder; import org.junit.BeforeClass; -import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; + +import static com.googlecode.catchexception.apis.BDDCatchException.*; +import static org.assertj.core.api.BDDAssertions.then; public class InvalidNamedConstructorArgsTest { - @Rule - public ExpectedException ex = ExpectedException.none(); private static SqlSessionFactory sqlSessionFactory; @@ -71,15 +68,14 @@ interface NoMatchingConstructorMapper { @Test public void noMatchingConstructorArgName() { - ex.expect(BuilderException.class); - ex.expectMessage(allOf( - containsString( - "'org.apache.ibatis.submitted.named_constructor_args.InvalidNamedConstructorArgsTest$NoMatchingConstructorMapper.select-void'"), - containsString("'org.apache.ibatis.submitted.named_constructor_args.User'"), - containsString("[noSuchConstructorArg]"))); - Configuration configuration = sqlSessionFactory.getConfiguration(); - configuration.addMapper(NoMatchingConstructorMapper.class); + when(configuration).addMapper(NoMatchingConstructorMapper.class); + + then(caughtException()).isInstanceOf(BuilderException.class) + .hasMessageContaining( + "'org.apache.ibatis.submitted.named_constructor_args.InvalidNamedConstructorArgsTest$NoMatchingConstructorMapper.select-void'") + .hasMessageContaining("'org.apache.ibatis.submitted.named_constructor_args.User'") + .hasMessageContaining("[noSuchConstructorArg]"); } interface ConstructorWithWrongJavaType { @@ -94,14 +90,13 @@ interface ConstructorWithWrongJavaType { @Test public void wrongJavaType() { - ex.expect(BuilderException.class); - ex.expectMessage(allOf( - containsString( - "'org.apache.ibatis.submitted.named_constructor_args.InvalidNamedConstructorArgsTest$ConstructorWithWrongJavaType.select-void'"), - containsString("'org.apache.ibatis.submitted.named_constructor_args.User'"), - containsString("[id]"))); Configuration configuration = sqlSessionFactory.getConfiguration(); - configuration.addMapper(ConstructorWithWrongJavaType.class); + when(configuration).addMapper(ConstructorWithWrongJavaType.class); + then(caughtException()).isInstanceOf(BuilderException.class) + .hasMessageContaining( + "'org.apache.ibatis.submitted.named_constructor_args.InvalidNamedConstructorArgsTest$ConstructorWithWrongJavaType.select-void'") + .hasMessageContaining("'org.apache.ibatis.submitted.named_constructor_args.User'") + .hasMessageContaining("[id]"); } interface ConstructorMissingRequiresJavaType { @@ -118,14 +113,12 @@ interface ConstructorMissingRequiresJavaType { @Test public void missingRequiredJavaType() { - ex.expect(BuilderException.class); - ex.expectMessage(allOf( - containsString( - "'org.apache.ibatis.submitted.named_constructor_args.InvalidNamedConstructorArgsTest$ConstructorMissingRequiresJavaType.select-void'"), - containsString("'org.apache.ibatis.submitted.named_constructor_args.User'"), - containsString("[id]"))); - Configuration configuration = sqlSessionFactory.getConfiguration(); - configuration.addMapper(ConstructorMissingRequiresJavaType.class); + when(configuration).addMapper(ConstructorMissingRequiresJavaType.class); + then(caughtException()).isInstanceOf(BuilderException.class) + .hasMessageContaining( + "'org.apache.ibatis.submitted.named_constructor_args.InvalidNamedConstructorArgsTest$ConstructorMissingRequiresJavaType.select-void'") + .hasMessageContaining("'org.apache.ibatis.submitted.named_constructor_args.User'") + .hasMessageContaining("[id]"); } } diff --git a/src/test/java/org/apache/ibatis/submitted/nested_query_cache/NestedQueryCacheTest.java b/src/test/java/org/apache/ibatis/submitted/nested_query_cache/NestedQueryCacheTest.java index c09d56e2548..69fc3d0e964 100644 --- a/src/test/java/org/apache/ibatis/submitted/nested_query_cache/NestedQueryCacheTest.java +++ b/src/test/java/org/apache/ibatis/submitted/nested_query_cache/NestedQueryCacheTest.java @@ -1,5 +1,5 @@ /** - * Copyright 2009-2015 the original author or authors. + * Copyright 2009-2016 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. @@ -26,7 +26,7 @@ import java.io.Reader; -import static org.hamcrest.CoreMatchers.sameInstance; +import static org.assertj.core.api.Assertions.assertThat; import static org.junit.Assert.*; public class NestedQueryCacheTest extends BaseDataTest { @@ -53,7 +53,7 @@ public void testThatNestedQueryItemsAreRetrievedFromCache() throws Exception { // ensure that author is cached final Author cachedAuthor = authorMapper.selectAuthor(101); - assertThat("cached author", author, sameInstance(cachedAuthor)); + assertThat(author).isSameAs(cachedAuthor); } finally { sqlSession.close(); } @@ -64,8 +64,8 @@ public void testThatNestedQueryItemsAreRetrievedFromCache() throws Exception { final BlogMapper blogMapper = sqlSession.getMapper(BlogMapper.class); // ensure that nested author within blog is cached - assertThat("blog author", blogMapper.selectBlog(1).getAuthor(), sameInstance(author)); - assertThat("blog author", blogMapper.selectBlogUsingConstructor(1).getAuthor(), sameInstance(author)); + assertThat(blogMapper.selectBlog(1).getAuthor()).isSameAs(author); + assertThat(blogMapper.selectBlogUsingConstructor(1).getAuthor()).isSameAs(author); } finally { sqlSession.close(); } @@ -93,7 +93,7 @@ public void testThatNestedQueryItemsAreRetrievedIfNotInCache() throws Exception Author cachedAuthor = authorMapper.selectAuthor(101); // ensure that nested author within blog is cached - assertThat("blog author", cachedAuthor, sameInstance(author)); + assertThat(cachedAuthor).isSameAs(author); } finally { sqlSession.close(); diff --git a/src/test/java/org/apache/ibatis/submitted/results_id/IdConflictTest.java b/src/test/java/org/apache/ibatis/submitted/results_id/IdConflictTest.java index a1a7f03fd47..edf112d7cf7 100644 --- a/src/test/java/org/apache/ibatis/submitted/results_id/IdConflictTest.java +++ b/src/test/java/org/apache/ibatis/submitted/results_id/IdConflictTest.java @@ -1,5 +1,5 @@ /** - * Copyright 2009-2015 the original author or authors. + * Copyright 2009-2017 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. @@ -16,23 +16,19 @@ package org.apache.ibatis.submitted.results_id; import org.apache.ibatis.session.Configuration; -import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; -public class IdConflictTest { +import static com.googlecode.catchexception.apis.BDDCatchException.*; +import static org.assertj.core.api.BDDAssertions.then; - @Rule - public ExpectedException ex = ExpectedException.none(); +public class IdConflictTest { @Test public void shouldFailOnDuplicatedId() throws Exception { - ex.expect(RuntimeException.class); - ex.expectMessage("Result Maps collection already contains value for org.apache.ibatis.submitted.results_id.IdConflictMapper.userResult"); - Configuration configuration = new Configuration(); - configuration.addMapper(IdConflictMapper.class); - configuration.getMappedStatements(); + when(configuration).addMapper(IdConflictMapper.class); + then(caughtException()).isInstanceOf(RuntimeException.class) + .hasMessage("Result Maps collection already contains value for org.apache.ibatis.submitted.results_id.IdConflictMapper.userResult"); } } diff --git a/src/test/java/org/apache/ibatis/submitted/sqlprovider/SqlProviderTest.java b/src/test/java/org/apache/ibatis/submitted/sqlprovider/SqlProviderTest.java index 31ea60b90df..a6ae5408490 100644 --- a/src/test/java/org/apache/ibatis/submitted/sqlprovider/SqlProviderTest.java +++ b/src/test/java/org/apache/ibatis/submitted/sqlprovider/SqlProviderTest.java @@ -1,5 +1,5 @@ /** - * Copyright 2009-2016 the original author or authors. + * Copyright 2009-2017 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. @@ -15,7 +15,6 @@ */ package org.apache.ibatis.submitted.sqlprovider; -import static org.hamcrest.core.Is.is; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertNull; @@ -37,17 +36,12 @@ import org.apache.ibatis.session.SqlSessionFactory; import org.apache.ibatis.session.SqlSessionFactoryBuilder; import org.junit.BeforeClass; -import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; public class SqlProviderTest { private static SqlSessionFactory sqlSessionFactory; - @Rule - public ExpectedException expectedException = ExpectedException.none(); - @BeforeClass public static void setUp() throws Exception { // create a SqlSessionFactory @@ -276,52 +270,64 @@ public void shouldGetUsersByNameWithParamName() { @Test public void methodNotFound() throws NoSuchMethodException { - expectedException.expect(BuilderException.class); - expectedException.expectMessage(is("Error creating SqlSource for SqlProvider. Method 'methodNotFound' not found in SqlProvider 'org.apache.ibatis.submitted.sqlprovider.SqlProviderTest$ErrorSqlBuilder'.")); - new ProviderSqlSource(new Configuration(), + try { + new ProviderSqlSource(new Configuration(), ErrorMapper.class.getMethod("methodNotFound").getAnnotation(SelectProvider.class)); + } catch (BuilderException e) { + e.getMessage().contains("Error creating SqlSource for SqlProvider. Method 'methodNotFound' not found in SqlProvider 'org.apache.ibatis.submitted.sqlprovider.SqlProviderTest$ErrorSqlBuilder'."); + } } @Test public void methodOverload() throws NoSuchMethodException { - expectedException.expect(BuilderException.class); - expectedException.expectMessage(is("Error creating SqlSource for SqlProvider. Method 'overload' is found multiple in SqlProvider 'org.apache.ibatis.submitted.sqlprovider.SqlProviderTest$ErrorSqlBuilder'. Sql provider method can not overload.")); - new ProviderSqlSource(new Configuration(), - ErrorMapper.class.getMethod("methodOverload", String.class).getAnnotation(SelectProvider.class)); + try { + new ProviderSqlSource(new Configuration(), + ErrorMapper.class.getMethod("methodOverload", String.class).getAnnotation(SelectProvider.class)); + } catch (BuilderException e) { + e.getMessage().contains("Error creating SqlSource for SqlProvider. Method 'overload' is found multiple in SqlProvider 'org.apache.ibatis.submitted.sqlprovider.SqlProviderTest$ErrorSqlBuilder'. Sql provider method can not overload."); + } } @Test public void notSqlProvider() throws NoSuchMethodException { - expectedException.expect(BuilderException.class); - expectedException.expectMessage(is("Error creating SqlSource for SqlProvider. Cause: java.lang.NoSuchMethodException: java.lang.Object.type()")); - new ProviderSqlSource(new Configuration(), new Object()); + try { + new ProviderSqlSource(new Configuration(), new Object()); + } catch (BuilderException e) { + e.getMessage().contains("Error creating SqlSource for SqlProvider. Cause: java.lang.NoSuchMethodException: java.lang.Object.type()"); + } } @Test public void notSupportParameterObjectOnMultipleArguments() throws NoSuchMethodException { - expectedException.expect(BuilderException.class); - expectedException.expectMessage(is("Error invoking SqlProvider method (org.apache.ibatis.submitted.sqlprovider.OurSqlBuilder.buildGetUsersByNameQuery). Cannot invoke a method that holds multiple arguments using a specifying parameterObject. In this case, please specify a 'java.util.Map' object.")); - new ProviderSqlSource(new Configuration(), + try { + new ProviderSqlSource(new Configuration(), Mapper.class.getMethod("getUsersByName", String.class, String.class).getAnnotation(SelectProvider.class)) - .getBoundSql(new Object()); + .getBoundSql(new Object()); + } catch (BuilderException e) { + e.getMessage().contains("Error invoking SqlProvider method (org.apache.ibatis.submitted.sqlprovider.OurSqlBuilder.buildGetUsersByNameQuery). Cannot invoke a method that holds multiple arguments using a specifying parameterObject. In this case, please specify a 'java.util.Map' object."); + } } @Test public void notSupportParameterObjectOnNamedArgument() throws NoSuchMethodException { - expectedException.expect(BuilderException.class); - expectedException.expectMessage(is("Error invoking SqlProvider method (org.apache.ibatis.submitted.sqlprovider.OurSqlBuilder.buildGetUsersByNameWithParamNameQuery). Cannot invoke a method that holds named argument(@Param) using a specifying parameterObject. In this case, please specify a 'java.util.Map' object.")); - new ProviderSqlSource(new Configuration(), + try { + new ProviderSqlSource(new Configuration(), Mapper.class.getMethod("getUsersByNameWithParamName", String.class).getAnnotation(SelectProvider.class)) - .getBoundSql(new Object()); + .getBoundSql(new Object()); + } catch (BuilderException e) { + e.getMessage().contains("Error invoking SqlProvider method (org.apache.ibatis.submitted.sqlprovider.OurSqlBuilder.buildGetUsersByNameWithParamNameQuery). Cannot invoke a method that holds named argument(@Param) using a specifying parameterObject. In this case, please specify a 'java.util.Map' object."); + } } @Test public void invokeError() throws NoSuchMethodException { - expectedException.expect(BuilderException.class); - expectedException.expectMessage(is("Error invoking SqlProvider method (org.apache.ibatis.submitted.sqlprovider.SqlProviderTest$ErrorSqlBuilder.invokeError). Cause: java.lang.reflect.InvocationTargetException")); - new ProviderSqlSource(new Configuration(), + try { + new ProviderSqlSource(new Configuration(), ErrorMapper.class.getMethod("invokeError").getAnnotation(SelectProvider.class)) - .getBoundSql(new Object()); + .getBoundSql(new Object()); + } catch (BuilderException e) { + e.getMessage().contains("Error invoking SqlProvider method (org.apache.ibatis.submitted.sqlprovider.SqlProviderTest$ErrorSqlBuilder.invokeError). Cause: java.lang.reflect.InvocationTargetException"); + } } @Test diff --git a/src/test/java/org/apache/ibatis/type/BlobByteObjectArrayTypeHandlerTest.java b/src/test/java/org/apache/ibatis/type/BlobByteObjectArrayTypeHandlerTest.java index 295c2806dd6..7f4f35a82d8 100644 --- a/src/test/java/org/apache/ibatis/type/BlobByteObjectArrayTypeHandlerTest.java +++ b/src/test/java/org/apache/ibatis/type/BlobByteObjectArrayTypeHandlerTest.java @@ -22,9 +22,7 @@ import java.io.*; import java.sql.Blob; -import static org.hamcrest.core.Is.is; -import static org.hamcrest.core.IsNull.nullValue; -import static org.junit.Assert.assertThat; +import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.Mockito.doNothing; import static org.mockito.Mockito.when; @@ -44,11 +42,11 @@ public void shouldSetParameter() throws Exception { doNothing().when(ps).setBinaryStream(positionCaptor.capture(), byteArrayCaptor.capture(), lengthCaptor.capture()); TYPE_HANDLER.setParameter(ps, 1, new Byte[]{1, 2}, null); ByteArrayInputStream actualIn = byteArrayCaptor.getValue(); - assertThat(positionCaptor.getValue(), is(1)); - assertThat(actualIn.read(), is(1)); - assertThat(actualIn.read(), is(2)); - assertThat(actualIn.read(), is(-1)); - assertThat(lengthCaptor.getValue(), is(2)); + assertThat(positionCaptor.getValue()).isEqualTo(1); + assertThat(actualIn.read()).isEqualTo(1); + assertThat(actualIn.read()).isEqualTo(2); + assertThat(actualIn.read()).isEqualTo(-1); + assertThat(lengthCaptor.getValue()).isEqualTo(2); } @Override @@ -59,7 +57,7 @@ public void shouldGetResultFromResultSetByName() throws Exception { when(rs.wasNull()).thenReturn(false); when(blob.length()).thenReturn((long)byteArray.length); when(blob.getBytes(1, 2)).thenReturn(byteArray); - assertThat(TYPE_HANDLER.getResult(rs, "column"), is(new Byte[]{1, 2})); + assertThat(TYPE_HANDLER.getResult(rs, "column")).isEqualTo(new Byte[]{1, 2}); } @@ -68,7 +66,7 @@ public void shouldGetResultFromResultSetByName() throws Exception { public void shouldGetResultNullFromResultSetByName() throws Exception { when(rs.getBlob("column")).thenReturn(null); when(rs.wasNull()).thenReturn(true); - assertThat(TYPE_HANDLER.getResult(rs, "column"), nullValue()); + assertThat(TYPE_HANDLER.getResult(rs, "column")).isNull(); } @Override @@ -79,7 +77,7 @@ public void shouldGetResultFromResultSetByPosition() throws Exception { when(rs.wasNull()).thenReturn(false); when(blob.length()).thenReturn((long)byteArray.length); when(blob.getBytes(1, 2)).thenReturn(byteArray); - assertThat(TYPE_HANDLER.getResult(rs, 1), is(new Byte[]{1, 2})); + assertThat(TYPE_HANDLER.getResult(rs, 1)).isEqualTo(new Byte[]{1, 2}); } @Override @@ -87,7 +85,7 @@ public void shouldGetResultFromResultSetByPosition() throws Exception { public void shouldGetResultNullFromResultSetByPosition() throws Exception { when(rs.getBlob(1)).thenReturn(null); when(rs.wasNull()).thenReturn(true); - assertThat(TYPE_HANDLER.getResult(rs, 1), nullValue()); + assertThat(TYPE_HANDLER.getResult(rs, 1)).isNull(); } @Override @@ -98,7 +96,7 @@ public void shouldGetResultFromCallableStatement() throws Exception { when(cs.wasNull()).thenReturn(false); when(blob.length()).thenReturn((long)byteArray.length); when(blob.getBytes(1, 2)).thenReturn(byteArray); - assertThat(TYPE_HANDLER.getResult(cs, 1), is(new Byte[]{1, 2})); + assertThat(TYPE_HANDLER.getResult(cs, 1)).isEqualTo(new Byte[]{1, 2}); } @Override @@ -106,7 +104,7 @@ public void shouldGetResultFromCallableStatement() throws Exception { public void shouldGetResultNullFromCallableStatement() throws Exception { when(cs.getBlob(1)).thenReturn(null); when(cs.wasNull()).thenReturn(true); - assertThat(TYPE_HANDLER.getResult(cs, 1), nullValue()); + assertThat(TYPE_HANDLER.getResult(cs, 1)).isNull(); } } \ No newline at end of file diff --git a/src/test/java/org/apache/ibatis/type/BlobInputStreamTypeHandlerTest.java b/src/test/java/org/apache/ibatis/type/BlobInputStreamTypeHandlerTest.java index 57f89273d76..a5052a15806 100644 --- a/src/test/java/org/apache/ibatis/type/BlobInputStreamTypeHandlerTest.java +++ b/src/test/java/org/apache/ibatis/type/BlobInputStreamTypeHandlerTest.java @@ -33,9 +33,7 @@ import java.io.*; import java.sql.Blob; -import static org.hamcrest.core.Is.is; -import static org.hamcrest.core.IsNull.nullValue; -import static org.junit.Assert.*; +import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; @@ -80,7 +78,7 @@ public void shouldGetResultFromResultSetByName() throws Exception { when(rs.getBlob("column")).thenReturn(blob); when(rs.wasNull()).thenReturn(false); when(blob.getBinaryStream()).thenReturn(in); - assertThat(TYPE_HANDLER.getResult(rs, "column"), is(in)); + assertThat(TYPE_HANDLER.getResult(rs, "column")).isEqualTo(in); } @@ -89,7 +87,7 @@ public void shouldGetResultFromResultSetByName() throws Exception { public void shouldGetResultNullFromResultSetByName() throws Exception { when(rs.getBlob("column")).thenReturn(null); when(rs.wasNull()).thenReturn(true); - assertThat(TYPE_HANDLER.getResult(rs, "column"), nullValue()); + assertThat(TYPE_HANDLER.getResult(rs, "column")).isNull(); } @Override @@ -99,7 +97,7 @@ public void shouldGetResultFromResultSetByPosition() throws Exception { when(rs.getBlob(1)).thenReturn(blob); when(rs.wasNull()).thenReturn(false); when(blob.getBinaryStream()).thenReturn(in); - assertThat(TYPE_HANDLER.getResult(rs, 1), is(in)); + assertThat(TYPE_HANDLER.getResult(rs, 1)).isEqualTo(in); } @Override @@ -107,7 +105,7 @@ public void shouldGetResultFromResultSetByPosition() throws Exception { public void shouldGetResultNullFromResultSetByPosition() throws Exception { when(rs.getBlob(1)).thenReturn(null); when(rs.wasNull()).thenReturn(true); - assertThat(TYPE_HANDLER.getResult(rs, 1), nullValue()); + assertThat(TYPE_HANDLER.getResult(rs, 1)).isNull(); } @Override @@ -117,7 +115,7 @@ public void shouldGetResultFromCallableStatement() throws Exception { when(cs.getBlob(1)).thenReturn(blob); when(cs.wasNull()).thenReturn(false); when(blob.getBinaryStream()).thenReturn(in); - assertThat(TYPE_HANDLER.getResult(cs, 1), is(in)); + assertThat(TYPE_HANDLER.getResult(cs, 1)).isEqualTo(in); } @Override @@ -125,7 +123,7 @@ public void shouldGetResultFromCallableStatement() throws Exception { public void shouldGetResultNullFromCallableStatement() throws Exception { when(cs.getBlob(1)).thenReturn(null); when(cs.wasNull()).thenReturn(true); - assertThat(TYPE_HANDLER.getResult(cs, 1), nullValue()); + assertThat(TYPE_HANDLER.getResult(cs, 1)).isNull(); } @Test @@ -145,7 +143,7 @@ public void integrationTest() throws IOException { // select (Blob -> InputStream) { BlobContent blobContent = mapper.findOne(1); - assertThat(new BufferedReader(new InputStreamReader(blobContent.getContent())).readLine(), is("Hello")); + assertThat(new BufferedReader(new InputStreamReader(blobContent.getContent())).readLine()).isEqualTo("Hello"); } } finally { session.close(); diff --git a/src/test/java/org/apache/ibatis/type/ByteObjectArrayTypeHandlerTest.java b/src/test/java/org/apache/ibatis/type/ByteObjectArrayTypeHandlerTest.java index 5dcbc5db8f0..cc56b298092 100644 --- a/src/test/java/org/apache/ibatis/type/ByteObjectArrayTypeHandlerTest.java +++ b/src/test/java/org/apache/ibatis/type/ByteObjectArrayTypeHandlerTest.java @@ -17,9 +17,7 @@ import org.junit.Test; -import static org.hamcrest.core.Is.is; -import static org.hamcrest.core.IsNull.nullValue; -import static org.junit.Assert.assertThat; +import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; @@ -40,7 +38,7 @@ public void shouldGetResultFromResultSetByName() throws Exception { byte[] byteArray = new byte[]{1, 2}; when(rs.getBytes("column")).thenReturn(byteArray); when(rs.wasNull()).thenReturn(false); - assertThat(TYPE_HANDLER.getResult(rs, "column"), is(new Byte[]{1, 2})); + assertThat(TYPE_HANDLER.getResult(rs, "column")).isEqualTo(new Byte[]{1, 2}); } @Override @@ -48,7 +46,7 @@ public void shouldGetResultFromResultSetByName() throws Exception { public void shouldGetResultNullFromResultSetByName() throws Exception { when(rs.getBytes("column")).thenReturn(null); when(rs.wasNull()).thenReturn(true); - assertThat(TYPE_HANDLER.getResult(rs, "column"), nullValue()); + assertThat(TYPE_HANDLER.getResult(rs, "column")).isNull(); } @Override @@ -57,7 +55,7 @@ public void shouldGetResultFromResultSetByPosition() throws Exception { byte[] byteArray = new byte[]{1, 2}; when(rs.getBytes(1)).thenReturn(byteArray); when(rs.wasNull()).thenReturn(false); - assertThat(TYPE_HANDLER.getResult(rs, 1), is(new Byte[]{1, 2})); + assertThat(TYPE_HANDLER.getResult(rs, 1)).isEqualTo(new Byte[]{1, 2}); } @Override @@ -65,7 +63,7 @@ public void shouldGetResultFromResultSetByPosition() throws Exception { public void shouldGetResultNullFromResultSetByPosition() throws Exception { when(rs.getBytes(1)).thenReturn(null); when(rs.wasNull()).thenReturn(true); - assertThat(TYPE_HANDLER.getResult(rs, 1), nullValue()); + assertThat(TYPE_HANDLER.getResult(rs, 1)).isNull(); } @Override @@ -74,7 +72,7 @@ public void shouldGetResultFromCallableStatement() throws Exception { byte[] byteArray = new byte[]{1, 2}; when(cs.getBytes(1)).thenReturn(byteArray); when(cs.wasNull()).thenReturn(false); - assertThat(TYPE_HANDLER.getResult(cs, 1), is(new Byte[]{1, 2})); + assertThat(TYPE_HANDLER.getResult(cs, 1)).isEqualTo(new Byte[]{1, 2}); } @Override @@ -82,7 +80,7 @@ public void shouldGetResultFromCallableStatement() throws Exception { public void shouldGetResultNullFromCallableStatement() throws Exception { when(cs.getBytes(1)).thenReturn(null); when(cs.wasNull()).thenReturn(true); - assertThat(TYPE_HANDLER.getResult(cs, 1), nullValue()); + assertThat(TYPE_HANDLER.getResult(cs, 1)).isNull(); } } \ No newline at end of file diff --git a/src/test/java/org/apache/ibatis/type/ClobReaderTypeHandlerTest.java b/src/test/java/org/apache/ibatis/type/ClobReaderTypeHandlerTest.java index 51f2a5a2b46..2855ffc6d63 100644 --- a/src/test/java/org/apache/ibatis/type/ClobReaderTypeHandlerTest.java +++ b/src/test/java/org/apache/ibatis/type/ClobReaderTypeHandlerTest.java @@ -33,10 +33,9 @@ import java.io.*; import java.sql.Clob; -import static org.hamcrest.core.Is.is; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertThat; +import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; @@ -144,7 +143,7 @@ public void integrationTest() throws IOException { // select (Clob -> Reader) { ClobContent clobContent = mapper.findOne(1); - assertThat(new BufferedReader(clobContent.getContent()).readLine(), is("Hello")); + assertThat(new BufferedReader(clobContent.getContent()).readLine()).isEqualTo("Hello"); } } finally { session.close(); diff --git a/src/test/java/org/apache/ibatis/type/usesjava8/Jsr310TypeHandlerRegistryTest.java b/src/test/java/org/apache/ibatis/type/usesjava8/Jsr310TypeHandlerRegistryTest.java index ae002dabab0..3f72763dbb7 100644 --- a/src/test/java/org/apache/ibatis/type/usesjava8/Jsr310TypeHandlerRegistryTest.java +++ b/src/test/java/org/apache/ibatis/type/usesjava8/Jsr310TypeHandlerRegistryTest.java @@ -15,15 +15,13 @@ */ package org.apache.ibatis.type.usesjava8; +import static org.assertj.core.api.Assertions.assertThat; + import org.apache.ibatis.io.Resources; import org.apache.ibatis.type.*; -import org.hamcrest.core.IsInstanceOf; import org.junit.Before; import org.junit.Test; -import static org.junit.Assert.*; -import static org.hamcrest.core.IsInstanceOf.*; - /** * Tests for auto-detect type handlers of mybatis-typehandlers-jsr310. * @@ -40,25 +38,25 @@ public void setup() { @Test public void testFor_v1_0_0() throws ClassNotFoundException { - assertThat(getTypeHandler("java.time.Instant"), instanceOf(InstantTypeHandler.class)); - assertThat(getTypeHandler("java.time.LocalDateTime"), instanceOf(LocalDateTimeTypeHandler.class)); - assertThat(getTypeHandler("java.time.LocalDate"), instanceOf(LocalDateTypeHandler.class)); - assertThat(getTypeHandler("java.time.LocalTime"), instanceOf(LocalTimeTypeHandler.class)); - assertThat(getTypeHandler("java.time.OffsetDateTime"), instanceOf(OffsetDateTimeTypeHandler.class)); - assertThat(getTypeHandler("java.time.OffsetTime"), instanceOf(OffsetTimeTypeHandler.class)); - assertThat(getTypeHandler("java.time.ZonedDateTime"), instanceOf(ZonedDateTimeTypeHandler.class)); + assertThat(getTypeHandler("java.time.Instant")).isInstanceOf(InstantTypeHandler.class); + assertThat(getTypeHandler("java.time.LocalDateTime")).isInstanceOf(LocalDateTimeTypeHandler.class); + assertThat(getTypeHandler("java.time.LocalDate")).isInstanceOf(LocalDateTypeHandler.class); + assertThat(getTypeHandler("java.time.LocalTime")).isInstanceOf(LocalTimeTypeHandler.class); + assertThat(getTypeHandler("java.time.OffsetDateTime")).isInstanceOf(OffsetDateTimeTypeHandler.class); + assertThat(getTypeHandler("java.time.OffsetTime")).isInstanceOf(OffsetTimeTypeHandler.class); + assertThat(getTypeHandler("java.time.ZonedDateTime")).isInstanceOf(ZonedDateTimeTypeHandler.class); } @Test public void testFor_v1_0_1() throws ClassNotFoundException { - assertThat(getTypeHandler("java.time.Month"), instanceOf(MonthTypeHandler.class)); - assertThat(getTypeHandler("java.time.Year"), instanceOf(YearTypeHandler.class)); + assertThat(getTypeHandler("java.time.Month")).isInstanceOf(MonthTypeHandler.class); + assertThat(getTypeHandler("java.time.Year")).isInstanceOf(YearTypeHandler.class); } @Test public void testFor_v1_0_2() throws ClassNotFoundException { - assertThat(getTypeHandler("java.time.YearMonth"), instanceOf(YearMonthTypeHandler.class)); - assertThat(getTypeHandler("java.time.chrono.JapaneseDate"), instanceOf(JapaneseDateTypeHandler.class)); + assertThat(getTypeHandler("java.time.YearMonth")).isInstanceOf(YearMonthTypeHandler.class); + assertThat(getTypeHandler("java.time.chrono.JapaneseDate")).isInstanceOf(JapaneseDateTypeHandler.class); } private TypeHandler getTypeHandler(String fqcn) throws ClassNotFoundException {