首页 > 解决方案 > com.test.controller.TestController 中的字段 testService 需要找不到类型为“com.test.service.TestService”的 bean

问题描述

我的应用程序在启动时运行良好,并且在为控制器编写单元测试时遇到了一个奇怪的问题。看起来非常基本和简单,但在这里停留了很长时间。我尝试了几种变体,包括 Mockito.Annotations,添加了 Baeldung 中提到的带有 bean 名称的限定符,但仍然得到基本错误。请协助解决此问题。

控制器类:

@Controller
@EnableAutoConfiguration
@Component
public class UserController {
    private static final Logger LOG = LoggerFactory.getLogger(UserController .class);

    @Autowired
    @Qualifier("userService")
    private userService userService;
}

服务接口:

public interface UserService {
    public User getUserById(Integer userId);
}

服务实施

@Service
public class UserServiceImpl implements UserService {
    private static final Logger LOG = LoggerFactory.getLogger(UserServiceImpl.class);
     @Autowired
    RecordService recordService;
    @Autowired
    UserDao userDao;
}

测试班

@RunWith(SpringJUnit4ClassRunner.class)
@SpringBootTest(classes = { UserController.class, UserService.class })
public class UserControllerTest {

    private MockMvc mockMvc;

    @InjectMocks
    UserController userController;

    @Mock
    UserService userService;

    @Before
    public void setup() {
        MockitoAnnotations.initMocks(this); // tried this to see if it helps
        mockMvc = MockMvcBuilders.standaloneSetup(testController).build();
    }

    @Test
    public void testWelcome() throws Exception {
        // Mocking Controller
        testController = mock(TestController.class);
        this.mockMvc.perform(get("/")).andExpect(status().isOk()) .andExpect(view().name("Welcome to Test-Service."));
    }
}

我的应用程序在启动时运行良好,并且在为控制器编写单元测试时遇到了一个奇怪的问题。看起来非常基本和简单,但在这里停留了很长时间。我尝试了几种变体,包括 Mockito.Annotations,添加了 Baeldung 中提到的带有 bean 名称的限定符,但仍然得到基本错误。请协助解决此问题。

***************************
APPLICATION FAILED TO START
    ***************************   
Field testService in com.test.controller.UserController required a bean of type 'com.service.UserService' that could not be found.

The injection point has the following annotations:
    - @org.springframework.beans.factory.annotation.Autowired(required=true)
    - @org.springframework.beans.factory.annotation.Qualifier(value=testService)
Action:
Consider defining a bean of type 'com.service.UserService' in your configuration.

标签: springspring-bootmockmvc

解决方案


因此,您正在加载一个控制器并希望模拟出控制器转向的实际服务。编写这样的测试有两个原因:

  1. 控制器有一些代码应该在“单元测试”级别进行检查。为此,您根本不需要 spring - 使用 Mockito Runner 运行测试,将服务的 Mock 注入“controller-class-under-test”并检查代码。一般建议/最佳实践是在控制器中保留最少的代码,并且不要在此级别创建大量代码。

  2. 您想检查控制器是否定义正确(包含所有映射、注释和所有内容)。对于这种测试,spring mvc 已经有一个您似乎正在尝试重新发明的解决方案:@WebMvcTest. 它执行以下操作:

    • 在内存中创建一个“mini mvc”(调度基础)——您可以与测试中的特殊 MockMVC 类进行交互,定义期望并“调用”请求。
    • 在这个模拟引擎中使用映射的控制器运行应用程序的一部分
    • 以不会加载@Service/@Repository注释类的方式自动配置 - 仅休息控制器。
    • 该服务将被模拟,并且可以在测试中指定对它的期望。

Mock MVC 测试有很多教程,例如快速谷歌搜索显示这一


推荐阅读