首页 > 解决方案 > (上下文)使用 JUnit4 和 Spring 进行 @RestController 测试的问题

问题描述

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

pom.xml 的主myapp文件夹具有模块部分:

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

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

myapp-dao
myapp-configuration
myapp-webapp

我正在为模块@RestController中的一个类编写 JUnit 测试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.properties问题myapp-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 上下文问题。该应用程序通常构建到 awar并部署到 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)}

这似乎很明显。

标签: javaspringspring-mvcmodel-view-controllerjunit4

解决方案


在控制器测试类之上使用上下文配置。 @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(...)
}

推荐阅读