spring mvc mock repository

时间:2015-12-03 16:26:33

标签: java spring spring-mvc

我正在学习spring并编写一个简单的spring boot应用程序。我想为我的控制器编写单元测试。控制器与存储库交互,我想为测试目的进行模拟。使用各种教程和文档,我得到了以下内容:

我的测试:

@RunWith(SpringJUnit4ClassRunner.class)
@SpringApplicationConfiguration(classes={TestConfiguration.class,MyWebappApplication.class})
@WebAppConfiguration
public class MyWebappApplicationTests {

private MockMvc mockMvc;

@Autowired
private MyRepository myRepositoryMock;

@Autowired
private WebApplicationContext webApplicationContext;

@Before
public void setUp() {
    mockMvc = MockMvcBuilders.webAppContextSetup(webApplicationContext).build();
}

@Test
public void contextLoads() throws Exception {


    MyEntity e1 = new MyEntity();
    e1.setId(1);
    e1.setDescription("e1");

    MyEntity e2 = new MyEntity();
    e2.setId(2);
    e2.setDescription("e2");

    when(myRepositoryMock.findAll()).thenReturn(Arrays.asList(e1, w2));



    mockMvc.perform(get("/"))
    .andExpect(status().isOk());

}

}

我提供模拟存储库的TestConfigiration:

@Configuration
public class TestConfiguration {

    @Bean
    public MyRepository myRepository() {
        return Mockito.mock(MyRepository.class);
    }

}

当我运行测试时,我没有将模拟的存储库注入到测试中,而是获得真实存储库,并在日志记录输出中获得以下行:

Overriding bean definition for bean 'myRepository' with a different definition: replacing [Root bean: class [null]; scope=; abstract=false; lazyInit=false; autowireMode=2; dependencyCheck=0; autowireCandidate=true; primary=true; factoryBeanName=testContext; factoryMethodName=ideaRepository; initMethodName=null; destroyMethodName=(inferred); defined in murdoch.suppriseme.TestContext] with [Root bean: class [org.springframework.data.jpa.repository.support.JpaRepositoryFactoryBean]; scope=; abstract=false; lazyInit=false; autowireMode=0; dependencyCheck=0; autowireCandidate=true; primary=false; factoryBeanName=null; factoryMethodName=null; initMethodName=null; destroyMethodName=null]

我尝试在bean上使用@Primary注释使其优先,但这不起作用。我错过了什么?

2 个答案:

答案 0 :(得分:0)

您应该能够通过遵守@Qualifier

来解决正确的实例

所以

@Configuration
public class TestConfiguration {

    @Bean
    @Qualifier("mock")
    public MyRepository myRepository() {
        return Mockito.mock(MyRepository.class);
    }

}

并在你的测试中

@Autowired
@Qualifier("mock")
private MyRepository myRepositoryMock;

答案 1 :(得分:-1)

您的测试是使用TestConfiguration.class,但您的类名为TestContext?