我正在学习Spring,并且我在同一个包
下创建了以下接口和类public interface CompactDisc {
public void play();
}
-
@Component
public class StgPeppers implements CompactDisc{
private String title = "Stg. Pepper's Lonely Hearts Club Band";
private String artist = "The Beatles";
@Override
public void play(){
System.out.println("Playing "+title+" by "+artist);
}
}
-
@Configuration
@ComponentScan
public class CDPlayerConfig {
}
使用
进行测试import junit.framework.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = CDPlayerConfig.class)
public class CDPlayerTest {
@Autowired
private CompactDisc cd;
@Test
public void cdShouldNotBeNull() {
Assert.assertNotNull(cd);
}
}
我正在从一本书中跟随这些例子,它要求测试它是否正常工作但不是如何做到这一点所以我在同一个包下创建了一个主要的类就是
public class Main {
public static void main(String[] args){
new CDPlayerTest().cdShouldNotBeNull();
}
}
在控制台中我有
Exception in thread "main" junit.framework.AssertionFailedError
at junit.framework.Assert.fail(Assert.java:55)
at junit.framework.Assert.assertTrue(Assert.java:22)
at junit.framework.Assert.assertNotNull(Assert.java:256)
at junit.framework.Assert.assertNotNull(Assert.java:248)
at automaticWiring.CDPlayerTest.cdShouldNotBeNull(CDPlayerTest.java:30)
at automaticWiring.Main.main(Main.java:17)
所有类的导入都是正确的,即使省略了,我使用带有Spring Web MVC框架的Netbeans webapp,我还必须将 JUnit 4.12 jar添加到库中,因为它不是在那里开始。 Spring代码有问题或我的测试方法不正确吗?
的web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="3.1" xmlns="http://xmlns.jcp.org/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd">
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/applicationContext.xml</param-value>
</context-param>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<servlet>
<servlet-name>dispatcher</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<load-on-startup>2</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>dispatcher</servlet-name>
<url-pattern>*.htm</url-pattern>
</servlet-mapping>
<session-config>
<session-timeout>
30
</session-timeout>
</session-config>
<welcome-file-list>
<welcome-file>redirect.jsp</welcome-file>
</welcome-file-list>
</web-app>
答案 0 :(得分:0)
你可以试试这个:
@RunWith(SpringRunner.class)
@SpringBootTest
public class CDPlayerTest {
@Autowired
private CompactDisc cd;
...
}
请记住,测试类在执行测试之前会加载整个应用程序上下文。