Spring 启动控制器测试 - 模拟存储库但测试实际服务

Spring boot controller test - mock repository but test actual service

我正在尝试在 Spring 引导 2 中编写测试 class,其中:

class 看起来像:

@RunWith(SpringRunner.class)
@WebMvcTest(MyController.class)
public class MyControllerTest {
    @Autowired
    private MockMvc mvc;
    @MockBean
    private MyRepositoryInterface myRepository;
    @Autowired
    private MyService myService;
    // tests follow ...
}

MyService 的(唯一)实现用 @Service 注释并允许通过其 @Autowired 构造函数注入存储库:

@Service
public class MyActualService implements MyService {
    private MyRepository repo;
    @Autowired
    public MyActualService(MyRepository repo) {
        this.repo = repo;
    }
    // ...
} 

我在 运行 测试时得到 NoSuchBeanDefinitionException,大致说明 "no MyService available"。

我怀疑我可能需要特定的测试配置才能获取服务,但我对可用的在线文献感到非常困惑。

有指针吗?

在咨询 docs (I did not read properly in the first instance), as pointed out by jonsharpe 之后,我设法找到了一个可行的解决方案:

@RunWith(SpringRunner.class)
@SpringBootTest
@AutoConfigureMockMvc
public class MyControllerTest {
    @Autowired
    private MockMvc mvc;
    @MockBean
    private MyRepositoryInterface myRepository;

    // no need to reference the service explicitly

    // ... tests follow
}

上面的代码在加载完整的应用程序配置时检索服务,并且只按照指示模拟存储库。

我可能可以编写一个临时配置来更好地满足要求,但这已经有效 "out of the box"。