代码之家  ›  专栏  ›  技术社区  ›  maloney

使用MockMVC测试注入

  •  2
  • maloney  · 技术社区  · 8 年前

    我正在编写一个Spring MVC集成测试,并希望模拟嵌入在类结构中的外部服务。然而,我似乎无法让模拟发挥作用。

    这是我的班级结构:

    控制器:

    @RestController
    public class Controller {
    
        private final MyService service;
    
        @Autowired
        public Controller(MyService service) {
            this.service = service;
        }
    
        @RequestMapping(value = "/send", method = POST, produces = APPLICATION_JSON_VALUE)
        public void send(@RequestBody Response response) {
            service.sendNotification(response);
        }
    }
    

    服务:

    @Service
    public class MyService {
    
        // Client is external service to be mocked
        private final Client client;
        private final Factory factory;
    
        @Autowired
        public MyService(Client client, Factory factory) {
            this.factory = factory;
            this.client = client;
        }
    
        public void sendNotification(Response response) {
            // Implemented code some of which will be mocked
        }
    }
    

    集成测试:

    @RunWith(SpringRunner.class)
    @SpringBootTest
    @AutoConfigureMockMvc
    public class IntegrationTest {
    
        MockMvc mockMvc;
    
        @Autowired
        MyService service;
    
        @Mock
        Client client;
    
        @Autowired
        Factory factory;
    
        @InjectMocks
        Controller controller;
    
        @Before
        public void setup() {
            initMocks(this);
            this.mockMvc = MockMvcBuilders.standaloneSetup(controller).build();
        }
    
        @Test
        public void test1() {
    
            String json = "{/"Somejson/":/"test/"}";
    
            mockMvc.perform(post("/send")
                .contentType(MediaType.APPLICATION_JSON)
                .content(json))
                .andExpect(status().isCreated());
        }
    }
    

    这将导致 service 结果为空。有人能看出我做错了什么吗?谢谢

    1 回复  |  直到 8 年前
        1
  •  4
  •   pvpkiran    8 年前

    好的是,您正在控制器和服务类中使用构造函数注入。这样可以更容易地使用模拟进行初始化

    这应该行得通。

    public class IntegrationTest {
    
        MockMvc mockMvc;
        MyService service;
        Controller controller;
    
        @Mock
        Client client;
    
        @Autowired
        Factory factory;
    
        @Before
        public void setup() {
            initMocks(this);
            MyService service = new MyService(client, factory);
            controller = new Controller(service);
            this.mockMvc = MockMvcBuilders.standaloneSetup(controller).build();
        }