Spring 3.2.1 を使用して spring-mvc テストを作成しようとしています。いくつかのチュートリアルに従って、これは簡単だと思いました。
これが私のテストです:
@RunWith( SpringJUnit4ClassRunner.class )
@ContextConfiguration( loader = AnnotationConfigContextLoader.class, classes = { JpaTestConfig.class } )
@WebAppConfiguration
public class HomeControllerTest {
@Resource
private WebApplicationContext webApplicationContext;
private MockMvc mockMvc;
@Test
public void testRoot() throws Exception {
mockMvc.perform(get("/").accept(MediaType.TEXT_PLAIN)).andDo(print())
// print the request/response in the console
.andExpect(status().isOk()).andExpect(content().contentType(MediaType.TEXT_PLAIN))
.andExpect(content().string("Hello World!"));
}
@Before
public void setUp() {
mockMvc = MockMvcBuilders.webAppContextSetup(webApplicationContext).build();
}
}
関連する pom.xml は次のとおりです。
<dependency>
<groupId>org.hamcrest</groupId>
<artifactId>hamcrest-all</artifactId>
<version>1.3</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.10</version>
<scope>test</scope>
<exclusions>
<exclusion>
<artifactId>hamcrest-core</artifactId>
<groupId>org.hamcrest</groupId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-test</artifactId>
<version>3.2.1.RELEASE</version>
</dependency>
次のテスト構成クラスがあります。
@Configuration
@EnableTransactionManagement
@ComponentScan( basePackages = { "com.myproject.service", "com.myproject.utility",
"com.myproject.controller" } )
@ImportResource( "classpath:applicationContext.xml" )
public class JpaTestConfig {
@Bean
public LocalContainerEntityManagerFactoryBean entityManagerFactoryBean() {
...
}
// various other services/datasource but not controllers
}
@WebAppConfiguration
追加すると、Spring が強制的に注入されることを理解しています。しかし、Eclipse 内からこのテストを実行すると、次のようになります。
原因: org.springframework.beans.factory.NoSuchBeanDefinitionException: 依存関係のタイプ [org.springframework.web.context.WebApplicationContext] の適格な Bean が見つかりません: この依存関係のオートワイヤー候補として適格な少なくとも 1 つの Bean が必要です。依存関係のアノテーション: {@org.springframework.beans.factory.annotation.Autowired(required=true)} at org.springframework.beans.factory.support.DefaultListableBeanFactory.raiseNoSuchBeanDefinitionException(DefaultListableBeanFactory.java:967) at org.springframework.beans. factory.support.DefaultListableBeanFactory.doResolveDependency(DefaultListableBeanFactory.java:837) at org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveDependency(DefaultListableBeanFactory.java:749) at org.springframework.beans.factory.annotation.
更新- Test Java Configuration クラスを変更する必要がありました
@Configuration
@EnableWebMvc
@ComponentScan( basePackages = { "...." } )
@EnableTransactionManagement
@ImportResource( "classpath:applicationContext.xml" )
public class JpaTestConfig extends WebMvcConfigurationSupport {
ただし、REST サービスを呼び出すことができるようになったにもかかわらず、データベース呼び出しを含む他のサービスを呼び出しているという問題があります。呼び出しと模擬応答をテストするための推奨される方法は何ですか。有効な条件と無効な条件をテストしたいと思います。