使用Spring,@ InjectMock带注释的测试目标不使用模拟

 每天吃的饱饱的 发布于 2023-01-31 10:45

我正在尝试对Spring 4.0.0 MVC应用程序进行单元测试.

我的控制器定义如下:

@Controller
@RequestMapping("/test")
public class TestCtrl {
    @Autowired
    private TestService testService;

    @Autowired
    private TestRessourceAssembler testRessourceAssembler;

    @Autowired
    private ResponseComposer responseComposer;

    @RequestMapping(value = "", method = RequestMethod.GET,produces = "application/json")
    public HttpEntity showAll(Pageable pageable) {   
        Page patr = testService.getAll(pageable);
        return responseComposer.composePage(patr,testRessourceAssembler);
    }

    @RequestMapping(value = "/{name}", method = RequestMethod.GET)
    public HttpEntity show(@PathVariable String name) {
        Test test = testService.getOne(name);
        if(test == null){
            return new ResponseEntity("Erreur !",HttpStatus.NOT_FOUND);
        }
        return responseComposer.compose(test,testRessourceAssembler);
    }
}

我的控制器单元测试如下:

@RunWith(SpringJUnit4ClassRunner.class)
@ActiveProfiles("test")
@WebAppConfiguration
@ContextConfiguration(classes = {ApplicationConfig.class, TestMongoConfig.class, RestConfig.class, WebMvcConfig.class})
public class TestCtrlTests{

    @InjectMocks
    TestCtrl testCtrl;

    @Mock
    TestService testService;

    @Autowired
    protected WebApplicationContext wac;

    protected MockMvc mockMvc;

    @Before
    public void setup(){
        MockitoAnnotations.initMocks(this);

        when(testService.getOne("jexiste")).thenReturn(new com.thalesgroup.ito.c2s.mc.portail.test.domain.Test("jexiste",1990));
        when(testService.getOne("plaf")).thenReturn(null);

        this.mockMvc = webAppContextSetup(this.wac).build();
       }

    @Test
    public void simpleGetAnswer() throws Exception{
        assertNotNull(mockMvc);
        mockMvc.perform(get("/test")).andExpect(status().isOk());
        mockMvc.perform(get("/test/jexiste")).andExpect(status().isOk());
        mockMvc.perform(get("/test/plaf")).andExpect(status().isNotFound());
    }
}

当我运行测试时,注入并使用"普通"TestService bean(我可以在日志中看到跟踪),而不是模拟.

所以我在互联网上阅读了一些内容并进行了更换

this.mockMvc = webAppContextSetup(this.wac).build();

this.mockMvc = standaloneSetup(TestCtrl.class).build();

但是,我知道会发生这种情况,在执行此操作时我没有更多的Spring上下文,因此我的PageableArgumentResolver和我的其他bean(testRessourceAssembler,responseComposer)不再被注入...所以它们是Null并且发生NullPointerException.

我的问题是:

1)我是在设计错误的东西?

2)如果没有,我怎样才能在我的控制器中注入一个模拟器,同时保持上下文中的其他bean?

谢谢你 !

撰写答案
今天,你开发时遇到什么问题呢?
立即提问
热门标签
PHP1.CN | 中国最专业的PHP中文社区 | PNG素材下载 | DevBox开发工具箱 | json解析格式化 |PHP资讯 | PHP教程 | 数据库技术 | 服务器技术 | 前端开发技术 | PHP框架 | 开发工具 | 在线工具
Copyright © 1998 - 2020 PHP1.CN. All Rights Reserved 京公网安备 11010802041100号 | 京ICP备19059560号-4 | PHP1.CN 第一PHP社区 版权所有