使用 MockMVC 测试注入

mal*_*ney 2 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);
    }
}
Run Code Online (Sandbox Code Playgroud)

服务:

@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
    }
}
Run Code Online (Sandbox Code Playgroud)

集成测试:

@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());
    }
}
Run Code Online (Sandbox Code Playgroud)

这导致service最终为空。谁能发现我做错了什么吗?谢谢

pvp*_*ran 6

好处是您在控制器和服务类中使用构造函数注入。这使得使用模拟初始化变得更容易

这应该有效。

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();
    }
Run Code Online (Sandbox Code Playgroud)