java的Spring学习2- junit
Posted zslm___
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了java的Spring学习2- junit相关的知识,希望对你有一定的参考价值。
1.maven依赖
<?xml version="1.0" encoding="UTF-8"?> <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>com.cnblog.gg</groupId> <artifactId>springTest</artifactId> <version>1.0-SNAPSHOT</version> <properties> <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> <spring.version>4.3.6.RELEASE</spring.version> <spring.junit>4.12</spring.junit> <springboot.version>1.5.1.RELEASE</springboot.version> </properties> <dependencies> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>${spring.junit}</version> <scope>test</scope> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-context</artifactId> <version>${spring.version}</version> </dependency> <!-- https://mvnrepository.com/artifact/org.springframework/spring-test --> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-test</artifactId> <version>${spring.version}</version> </dependency> </dependencies> <build> <plugins> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-compiler-plugin</artifactId> <configuration> <source>1.8</source> <target>1.8</target> </configuration> </plugin> </plugins> </build> </project>
2. java代码
package com.cnblog.gg; public interface VedioPlayer { void play(); }
package com.cnblog.gg; import org.springframework.stereotype.Component; @Component("mp3") public class Mp3Player implements VedioPlayer { @Override public void play() { System.out.println("I am mp3 player"); } }
3.spring扫描
package com.cnblog.gg; import org.springframework.context.annotation.ComponentScan; import org.springframework.context.annotation.Configuration; @Configuration @ComponentScan public class VedioPlayerConfig { }
4.单元测试代码
package com.cnblog.gg; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import javax.annotation.Resource; import static org.junit.Assert.*; @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration(classes = VedioPlayerConfig.class) public class Mp3PlayerTest { @Autowired private VedioPlayer player; @Resource(name="mp3") private VedioPlayer player2; @Test public void playNotNull() { assertNotNull(player); assertNotNull(player2); assertTrue (player==player2); } }
以上是关于java的Spring学习2- junit的主要内容,如果未能解决你的问题,请参考以下文章
java spring项目的controller层的代码怎么用junit写单元测试用例
Spring:概述,IOC(Bean管理),整合Web项目,整合JUnit单元测试
使用Junit测试一个 spring静态工厂实例化bean 的例子,所有代码都没有问题,但是出现java.lang.IllegalArgumentException异常