(上下文)使用JUnit4和Spring进行@RestController测试的问题。

问题描述 投票:0回答:1

我有3个独立的项目,由pom.xml绑定。

myapp 文件夹中的pom.xml有模块部分。

<modules>
    <module>myapp-dao</module>
    <module>myapp-webapp</module>
    <module>myapp-configuration</module>
</modules>

里面有3个项目 myapp 文件夹(每个文件夹都有自己的pom.xml)。

myapp-dao
myapp-configuration
myapp-webapp

我正在写一个JUnit测试,为一个 @RestController 课堂上 myapp-webapp 模块(不要担心@Test的内容,它只是一个骨架,当我能够运行测试时,它将被扩展)。

@RunWith(SpringRunner.class)
@AutoConfigureMockMvc
@WebMvcTest(ContentController.class)
public class ContentControllerTest {

    @Autowired
    private MockMvc mvc;

    @MockBean
    private ContentService contentService;
    @MockBean
    private HyperlinkReferenceService hyperlinkReferenceService;

    @Test
    public void givenEmployees_whenGetEmployees_thenReturnJsonArray() throws Exception {

        given(contentService.findContentUsedAsTemplateIn(1, 0)).willReturn(null);

        mvc.perform(get("/portal/content/1/references/usedAsTemplateIn").contentType(MediaType.APPLICATION_JSON))
                .andExpect(status().isOk()).andExpect(jsonPath("$", hasSize(1)));
    }

}

当我试图运行测试时,我得到:

java.lang.IllegalStateException: Failed to load ApplicationContext
org.springframework.beans.factory.BeanDefinitionStoreException: Failed to parse configuration class [com.pro4people.msg.ServletInitializer]; nested exception is java.io.FileNotFoundException: class path resource [myapp.properties] cannot be opened because it does not exist

我已经解决了这个问题,复制了 myapp-configuration/target/myapp.propertiesmyapp-webapp/src/main/test/resources/myapp.properties

这样解决了上面的问题,但是另一个问题就出来了。

java.lang.IllegalStateException: Failed to load ApplicationContext

Description:
Field userRepository in com.company.myapp.service.UserServiceImpl required a bean of type 'com.company.myapp.repository.UserRepository' that could not be found.
Action:
Consider defining a bean of type 'com.company.myapp.repository.UserRepository' in your configuration.

但实际上,我在这个测试中根本没有使用UserRepository,所以我推测是Spring上下文的某个地方出现了问题。应用程序通常是按照 war 并部署到Tomcat上,而且只在其 wared 状态下,一切都正确注入和绑定。

怎样才能省略这个问题?不管我想做什么,测试都是在提升spring上下文,而当我删除了 @WebMvcTest(ContentController.class),我明白了。

org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'com.company.myapp.controller.portal.json.ContentControllerTest': Unsatisfied dependency expressed through field 'mvc'; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type 'org.springframework.test.web.servlet.MockMvc' available: expected at least 1 bean which qualifies as autowire candidate. Dependency annotations: {@org.springframework.beans.factory.annotation.Autowired(required=true)}

这似乎是显而易见的。

java spring spring-mvc model-view-controller junit4
1个回答
2
投票

在你的控制器测试类之上使用Context配置。 @ContextConfiguration(classes = {ContentController.class})

Below code works for unit test for controller.

@RunWith(MockitoJUnitRunner.class)
@WebAppConfiguration
@ContextConfiguration(classes = {ContentController.class})
public class ContentController {

 private MockMvc mockMvc;

 @InjectMocks
 private ContentController contentController;

@Mock
private ContentService contentService;

....

    /**
     * Configure the mockMvc with Controller.
     */
    @Before
    public void setup() {
        mockMvc = MockMvcBuilders.standaloneSetup(contentController).build();
    }


  @Test
  your test here() {
 //use Mockito.when(statement).thenReturn(value);
  //rest remain same using mockMVC
   mockMvc.perform(...)
}
© www.soinside.com 2019 - 2024. All rights reserved.