注入MockMVC测试

时间:2018-02-13 11:51:17

标签: java spring spring-mvc

我正在编写一个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最终为null。谁能发现我做错了什么?感谢

1 个答案:

答案 0 :(得分:3)

好的是你在Controller和Service类中使用构造函数注入。这样可以更容易地使用模拟进行初始化

这应该有效。

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