Men*_*ena 6 spring integration-testing spring-boot
我正在尝试在Spring boot 2中编写一个测试类,其中:
这个类看起来像:
@RunWith(SpringRunner.class)
@WebMvcTest(MyController.class)
public class MyControllerTest {
@Autowired
private MockMvc mvc;
@MockBean
private MyRepositoryInterface myRepository;
@Autowired
private MyService myService;
// tests follow ...
}
Run Code Online (Sandbox Code Playgroud)
的(唯一)实现MyService
带有注释@Service
并允许通过其@Autowired
构造函数注入存储库:
@Service
public class MyActualService implements MyService {
private MyRepository repo;
@Autowired
public MyActualService(MyRepository repo) {
this.repo = repo;
}
// ...
}
Run Code Online (Sandbox Code Playgroud)
我NoSuchBeanDefinitionException
在运行测试时得到了一个,广泛地说“没有MyService
可用的”。
我怀疑我可能需要特定的测试配置来获取服务,但我对可用的在线文献感到非常困惑。
任何指针?
正如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
}
Run Code Online (Sandbox Code Playgroud)
上面在加载完整的应用程序配置时检索服务,并且仅按照指示模拟存储库。
我可能可以编写一个临时配置来更好地满足要求,但这已经“开箱即用”了。
归档时间: |
|
查看次数: |
3336 次 |
最近记录: |