依赖项失败的Spring控制器测试

时间:2018-11-22 18:43:38

标签: java spring-mvc spring-test-mvc

我有以下控制器类:

mutable struct Env
end

function step(env, action:UInt32)
    return ones(8), 1.0, true, Dict()
end

function reset(env)
    return ones(8)
end

如您所见,它接受一个依赖关系。这一切在服务器上都可以正常运行。但是,在测试时,它会失败:

@Controller
public class HelloController {

    private final HelloService service;

    public HelloController(HelloService service) {
        this.service = service;
    }

    @RequestMapping("/hello")
    public @ResponseBody String greeting() {
        return service.greet();
    }

}

下面是target / surefire-reports /

中日志文件的输出
@RunWith(SpringRunner.class)
@WebMvcTest(HelloController.class)
public class WebLayerTest {

    @Autowired
    private MockMvc mockMvc;

    @Test
    public void shouldReturnDefaultMessage() throws Exception {
    this.mockMvc.perform(get("/hello")).andDo(print()).andExpect(status().isOk())
                .andExpect(content().string(containsString("Hello World")));
    }
}

我知道------------------------------------------------------------------------------- Test set: biz.martyn.footy.WebLayerTest ------------------------------------------------------------------------------- Tests run: 1, Failures: 0, Errors: 1, Skipped: 0, Time elapsed: 2.278 s <<< FAILURE! - in biz.martyn.footy.WebLayerTest shouldReturnDefaultMessage(biz.martyn.footy.WebLayerTest) Time elapsed: 0.005 s <<< ERROR! java.lang.IllegalStateException: Failed to load ApplicationContext Caused by: org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'helloController' defined in file [/home/martyn/eclipse-workspace/Footy/target/classes/biz/martyn/footy/controller/HelloController.class]: Unsatisfied dependency expressed through constructor parameter 0; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type 'biz.martyn.footy.service.HelloService' available: expected at least 1 bean which qualifies as autowire candidate. Dependency annotations: {} Caused by: org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type 'biz.martyn.footy.service.HelloService' available: expected at least 1 bean which qualifies as autowire candidate. Dependency annotations: {} 允许我创建依赖项的模拟,但是如果我不想模拟它,该怎么办?在这里,我很高兴能将正常的依赖实例正常使用。或者,是因为我只是在测试Web层时,它没有像在运行完整应用程序时那样实例化控制器?

更新

我还尝试了@MockBean注入而不是构造函数。我的应用程序正常运行,因此将依赖项带入控制器,但测试失败。下面是更新的控制器:

@Autowired

1 个答案:

答案 0 :(得分:1)

@WebMvcTest将禁用完全自动配置,而仅应用与MVC测试相关的配置(即@Controller@ControllerAdvice@JsonComponent,Converter / GenericConverter,Filter,WebMvcConfigurer和HandlerMethodArgumentResolver bean,但不能使用@Component@Service@Repository bean,因此必须使用@MockBean来满足依赖性。