Spring没有在测试中调用@Bean方法

时间:2018-04-27 15:44:17

标签: java spring junit mockito

我有一个@Repository的存储库@WithUserDetails。该存储库由我的其中一个控制器使用。我想测试的是我的其他控制器的授权是否正常工作,因此我的测试使用MyRepository。我想按照this tutorial模拟对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

通过一些调试我发现我的@Repository interface MyRepository extends CrudRepository<MyEntity, Long> {} 方法没有被调用。

的src /主/爪哇/ com。示例

MyRepository

@Profile("test")
@Configuration
public class MockConfig
{
    @Bean
    @Primary
    public MyRepository myRepository()
    {
        return Mockito.mock(MyRepository.class);
    }
}

的src /测试/ JAVA / com。示例

MockConfig

@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());
    }
}

MyTestClass

span

2 个答案:

答案 0 :(得分:2)

尝试使用How to exclude a @Repository from component scan when using Spring Data Rest

中提出的解决方案

将以下注释添加到测试类

@EnableJpaRepositories(excludeFilters = {@ComponentScan.Filter(type = FilterType.ASSIGNABLE_TYPE, classes = {MyRepository.class})})
class MyTestClass
(...)

答案 1 :(得分:0)

如果你想为你的测试类模拟依赖项(例如存储库),我建议你使用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());
        ...
    }

有一些参考here

如果您坚持使用当前实现进行测试,可能是Spring数据扫描了MyRepository并且bean已经初始化了。您可能希望按照user2456718的建议禁用组件扫描。