Tag Archives: junit

The usage of Java JUnit unit test and the solution of initialization error

Usage:
1. Select project – right click – build path – add Libraries – JUnit – next – junit4 – finish
2. Write @ test on the method body to be tested

Note:
1. The test method must be modified with public
2. The return value must be void
3. There can be no parameters in the method
4. There can be no class named test under the package
if the test code is OK, an error is still reported, initialization error is not reported in other classes,
it may be because there is an error method in this class
2 Or there are multiple @ test annotations in a class, one of which adds static or has other errors.

Spring integrates JUnit configuration

2. In junit unit tests, executing
junit without a main method determines which methods in the current Test class have @test annotations
junit lets annotated methods execute
. Junit doesn’t matter if we’re using the spring framework
4. When the test method executes without an IOC container, a null pointer exception is raised even when the @Autowried annotation is written
Solution:
Spring integration junit configuration
1. 2. Replace the main method with the @runwith
3 provided by Spring with an annotation provided by junit. Runner told spring, spring and ioc creation is based on XML and annotation, and show the position of
annotation-based: @ ContextConfiguration (classes = SpringConfiguration. Class)
based on the configuration file: @ ContextConfiguration (locations = “classpath: bean. XML”)

Spring configuration transaction, JUnit unit test error “failed to load ApplicationContext”

problem:

Junit unit test code is as follows:

package cn.muke.spring.demo2;

import javax.annotation.Resource;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;

/**
 * Spring的声明式事务管理方式一的测试类
 * @author CX
 *
 */
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration("classpath:applicationContext2.xml")
public class SpringDemo2 {
	
	/**
	 * 因为要测试业务层的实现类,所以引用业务层的接口
	 */
	@Resource(name="accountService")
	private AccountService accountService;	
	
    /**
	 * 转账案例:
	 */
	@Test
	public void demo1() {
		accountService.transfer("aaa", "bbb", 200d);
	}
}

Applicationcontext2.xml configuration is as follows :

<?xml version="1.0" encoding='UTF-8'?>
<beans xmlns="http://www.springframework.org/schema/beans"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xmlns:context="http://www.springframework.org/schema/context"
	xmlns:aop="http://www.springframework.org/schema/aop"
	xmlns:tx="http://www.springframework.org/schema/tx"
	xsi:schemaLocation="http://www.springframework.org/schema/beans
	http://www.springframework.org/schema/beans/spring-beans.xsd
	http://www.springframework.org/schema/context
	http://www.springframework.org/schema/context/spring-context.xsd
	http://www.springframework.org/schema/aop
	http://www.springframework.org/schema/aop/spring-aop.xsd
	http://www.springframework.org/schema/tx
	http://www.springframework.org/schema/tx/spring-tx.xsd">
		
	<!-- 引入外部的属性文件 -->
	<context:property-placeholder location="classpath:jdbc.properties"/>
	
	<!-- 配置c3p0连接池 -->
	<bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
		<property name="driverClass" value="${jdbc.driverClass}"/>
		<property name="jdbcUrl" value="${jdbc.url}"/>
		<property name="user" value="${jdbc.username}"/>
		<property name="password" value="${jdbc.password}"/>
	</bean>
		
	<!-- 配置业务层类 -->
	<bean id="accountService" class="cn.muke.spring.demo2.AccountServiceImpl">
		<!-- 业务层注入DAO方式 -->
		<property name="accoutDAO" ref="accountDAO"/>		
	</bean>
	
	<!-- 配置DAO类 -->
	<bean id="accountDAO" class="cn.muke.spring.demo2.AccountDAOImpl">
		<!-- 在XML中注入连接池 ,在DAO实现类中继承JdbcDaoSupport,两者都可以 -->
		<property name="dataSource" ref="dataSource"/>
	</bean>
		
</beans>

accountService and accountDao should be ok, that is, the DataSource is injected into the dao, and the dao error message is injected into the service as follows:

2018-12-29 15:44:21 INFO  org.springframework.beans.factory.xml.XmlBeanDefinitionReader  Loading XML bean definitions from class path resource [applicationContext2.xml]
2018-12-29 15:44:21 INFO  org.springframework.context.support.GenericApplicationContext  Refreshing org.springframework.context.support.GenericApplicationContext@6537cf78: startup date [Sat Dec 29 15:44:21 CST 2018]; root of context hierarchy
2018-12-29 15:44:21 ERROR org.springframework.test.context.TestContextManager  Caught exception while allowing TestExecutionListener [org.springframework.test.context.support.DependencyInjectionTestExecutionListener@40f08448] to prepare test instance [cn.muke.spring.demo2.SpringDemo2@6bf256fa]
java.lang.IllegalStateException: Failed to load ApplicationContext
	at org.springframework.test.context.TestContext.getApplicationContext(TestContext.java:157)
	at org.springframework.test.context.support.DependencyInjectionTestExecutionListener.injectDependencies(DependencyInjectionTestExecutionListener.java:109)
	at org.springframework.test.context.support.DependencyInjectionTestExecutionListener.prepareTestInstance(DependencyInjectionTestExecutionListener.java:75)
	at org.springframework.test.context.TestContextManager.prepareTestInstance(TestContextManager.java:313)
	at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.createTest(SpringJUnit4ClassRunner.java:211)
	at org.springframework.test.context.junit4.SpringJUnit4ClassRunner$1.runReflectiveCall(SpringJUnit4ClassRunner.java:288)
	at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
	at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.methodBlock(SpringJUnit4ClassRunner.java:284)
	at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:231)
	at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:88)
	at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290)
	at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71)
	at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288)
	at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58)
	at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268)
	at org.springframework.test.context.junit4.statements.RunBeforeTestClassCallbacks.evaluate(RunBeforeTestClassCallbacks.java:61)
	at org.springframework.test.context.junit4.statements.RunAfterTestClassCallbacks.evaluate(RunAfterTestClassCallbacks.java:71)
	at org.junit.runners.ParentRunner.run(ParentRunner.java:363)
	at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.run(SpringJUnit4ClassRunner.java:174)
	at org.eclipse.jdt.internal.junit4.runner.JUnit4TestReference.run(JUnit4TestReference.java:89)
	at org.eclipse.jdt.internal.junit.runner.TestExecution.run(TestExecution.java:41)
	at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:541)
	at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:763)
	at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:463)
	at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:209)
Caused by: java.lang.IllegalArgumentException
	at org.springframework.asm.ClassReader.<init>(Unknown Source)
	at org.springframework.asm.ClassReader.<init>(Unknown Source)
	at org.springframework.asm.ClassReader.<init>(Unknown Source)
	at org.springframework.core.type.classreading.SimpleMetadataReader.<init>(SimpleMetadataReader.java:52)
	at org.springframework.core.type.classreading.SimpleMetadataReaderFactory.getMetadataReader(SimpleMetadataReaderFactory.java:80)
	at org.springframework.core.type.classreading.CachingMetadataReaderFactory.getMetadataReader(CachingMetadataReaderFactory.java:101)
	at org.springframework.core.type.classreading.SimpleMetadataReaderFactory.getMetadataReader(SimpleMetadataReaderFactory.java:76)
	at org.springframework.context.annotation.ConfigurationClassUtils.checkConfigurationClassCandidate(ConfigurationClassUtils.java:70)
	at org.springframework.context.annotation.ConfigurationClassPostProcessor.processConfigBeanDefinitions(ConfigurationClassPostProcessor.java:253)
	at org.springframework.context.annotation.ConfigurationClassPostProcessor.postProcessBeanDefinitionRegistry(ConfigurationClassPostProcessor.java:223)
	at org.springframework.context.support.AbstractApplicationContext.invokeBeanFactoryPostProcessors(AbstractApplicationContext.java:630)
	at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:461)
	at org.springframework.test.context.support.AbstractGenericContextLoader.loadContext(AbstractGenericContextLoader.java:106)
	at org.springframework.test.context.support.AbstractGenericContextLoader.loadContext(AbstractGenericContextLoader.java:57)
	at org.springframework.test.context.support.AbstractDelegatingSmartContextLoader.delegateLoading(AbstractDelegatingSmartContextLoader.java:100)
	at org.springframework.test.context.support.AbstractDelegatingSmartContextLoader.loadContext(AbstractDelegatingSmartContextLoader.java:248)
	at org.springframework.test.context.TestContext.loadApplicationContext(TestContext.java:124)
	at org.springframework.test.context.TestContext.getApplicationContext(TestContext.java:148)
	... 24 more

solution:

this is because Spring is in conflict with the JDK version, Spring3.* is in conflict with JDK 1.8. So you need to change the JDK to 1.7 or upgrade to Spring4.*.

How to Fix “junit.framework.Comparison Failure Expected: but was”

junit.framework.ComparisonFailure: expected:< . > But was: solution

an error occurred while running the MVN instruction: MVN clean test using the DOS window:

[ERROR] Please refer to D:\ learning gadgets \ first semester of junior \ enterprise application construction and management \ experiments \maven_demo\target\surefire-reports for the individual test results

error display from the surefire – reports file to find errors, check the surefire – reports file:

error body is this:
junit.framework.ComparisonFailure: expected:< Hello [World]guoyilin! > but was:< Hello []guoyilin! >

in the test file called assetEquals method, the method to compare the the statement with a specified in parentheses, if different than the error


you can see, The statement returned in the sayHello method is different from the statement specified in the test module, and that’s where the error is, just change the statement to be the same.