[英]Spring not calling @Bean method in tests
我有一个Repository MyRepository
,它是一个@Repository
。 该存储库供我的其他控制器之一使用。 我要测试的是剩余控制器的授权是否正常工作,因此我的测试使用@WithUserDetails
。 我想通过遵循本教程来模拟对MyRepository
的调用。 当我运行测试时,我会收到一条异常消息:
org.mockito.exceptions.misusing.MissingMethodInvocationException:
when() requires an argument which has to be 'a method call on a mock'.
For example:
when(mock.getArticles()).thenReturn(articles);
Also, this error might show up because:
1. you stub either of: final/private/equals()/hashCode() methods.
Those methods *cannot* be stubbed/verified.
Mocking methods declared on non-public parent classes is not supported.
2. inside when() you don't call method on mock but on some other object.
通过一些调试,我发现我的MockConfig#myRepository
方法没有被调用。
src / main / java / com.example
我的资料库
@Repository
interface MyRepository extends CrudRepository<MyEntity, Long> {}
src / test / java / com.example
模拟配置
@Profile("test")
@Configuration
public class MockConfig
{
@Bean
@Primary
public MyRepository myRepository()
{
return Mockito.mock(MyRepository.class);
}
}
MyTestClass
@ActiveProfiles("test")
@AutoConfigureMockMvc
@RunWith(SpringRunner.class)
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT, classes = Application.class)
@TestExecutionListeners({
DependencyInjectionTestExecutionListener.class
})
class MyTestClass
{
@Autowired
private MockMvc mvc;
@Autowired
private MyRepository myRepository;
@Test
@WithUserDetails("some_user")
public void testWithCorrectPermissions()
{
long entityId = 1;
MyEntity mockReturnValue = new MyEntity();
Mockito.when(myRepository.findOne(entityId)).thenReturn(mockReturnValue);
Mockito.when(myRepository.save(mockReturnValue)).thenReturn(mockReturnValue);
this.mockMvc.perform(post("my/api/path")).andExpect(status().isOk());
}
}
尝试使用使用Spring Data Rest时如何从组件扫描中排除@Repository中提出的解决方案
将以下注释添加到测试类
@EnableJpaRepositories(excludeFilters = {@ComponentScan.Filter(type = FilterType.ASSIGNABLE_TYPE, classes = {MyRepository.class})})
class MyTestClass
(...)
如果您想模拟测试类的依赖项(例如存储库),我建议您使用MockitoJUnitRunner.class,因为SpringRunner.class将初始化Spring应用程序的内容,这将导致测试变慢并且依赖于所需的更多依赖项在您的项目配置上。
因此,对于您的MyTestClass
@RunWith(MockitoJUnitRunner.class)
public class MyTestClass{
@Mock
private MyRepository myRepository;
private MyTest myTest;
@Before
public void setUp() throws Exception {
myTest = new MyTest(myRepository);
}
@Test
public void test(){
...
when(myRepository.get(anyInt()).thenReturn(new MyEntity());
...
}
有一定的参考这里 。
如果您坚持使用当前的实现进行测试,则可能是MyRepository被Spring Data扫描了,而Bean被它初始化了。 您可能要按照user2456718的建议禁用组件扫描。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.