2013-10-31 35 views
0

我寫這篇文章:未找到默認構造函數;嵌套異常org.springframework.test.context.TestContext。 <init>()

http://www.javacodegeeks.com/2013/07/unit-testing-of-spring-mvc-controllers-normal-controllers.html

我嘗試寫我的控制器測試:

我的代碼:

import static org.fest.assertions.Assertions.assertThat; 

import org.junit.Test; 
import org.junit.runner.RunWith; 
import org.springframework.test.context.ContextConfiguration; 
import org.springframework.test.context.TestContext; 
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; 
import org.springframework.test.context.web.WebAppConfiguration; 
import org.springframework.web.context.WebApplicationContext; 

@RunWith(SpringJUnit4ClassRunner.class) 
@ContextConfiguration(classes = {TestContext.class, WebApplicationContext.class}) 
@WebAppConfiguration 
public class SiteControllerTest { 

    @Test 
    public void shouldReturnCorrectSite() throws Exception { 
     assertThat(true).isTrue(); 
    } 



} 

當我運行試驗我得到這樣的例外:

No default constructor found; nested exception is java.lang.NoSuchMethodException: org.springframework.test.context.TestContext.() at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.instantiateBean(AbstractAutowireCapableBeanFactory.java:1007) 


java.lang.IllegalStateException: Failed to load ApplicationContext 
at org.springframework.test.context.CacheAwareContextLoaderDelegate.loadContext(CacheAwareContextLoaderDelegate.java:99) 

... 

Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'testContext': Instantiation of bean failed; nested exception is org.springframework.beans.BeanInstantiationException: Could not instantiate bean class [org.springframework.test.context.TestContext]: No default constructor found; nested exception is java.lang.NoSuchMethodException: org.springframework.test.context.TestContext.<init>() 
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.instantiateBean(AbstractAutowireCapableBeanFactory.java:1007) 

我做錯了什麼?

+0

那麼,您的TestContext類沒有無參數構造函數,正如消息所示。 –

+0

TestContext.class是org.springframework.test.context中的一個類。我能做什麼? – user6778654

+1

這並不意味着與'ContextConfiguration'一起使用。我認爲他們在鏈接教程中創建了自己的TestContext類。 –

回答

0

在原來的文章,你應該定義的TestContext類在類路徑,例如:

@Configuration 
public class TestContext { 

    @Bean 
    public MessageSource messageSource() { 
     ResourceBundleMessageSource messageSource = new ResourceBundleMessageSource(); 

     messageSource.setBasename("i18n/messages"); 
     messageSource.setUseCodeAsDefaultMessage(true); 

     return messageSource; 
    } 

    @Bean 
    public TodoService todoService() { 
     return Mockito.mock(TodoService.class); 
    } 
} 

行吟替代,可直接使用的測試,而不是Java類的XML文件:

@ContextConfiguration(locations = {"classpath:testContext.xml", "classpath:exampleApplicationContext-web.xml"})