【发布时间】:2018-12-30 02:11:12
【问题描述】:
我有一个 Spring Boot 应用程序,我正在其中创建 REST Web 服务 使用 MVC 模式。
我有一个控制器、服务和 DAO 类,我使用 @Autowired 注解来调用服务和 DAO 层的方法。
当我使用 mockito 创建 JUnit 测试时,值会进入控制器,但不会从控制器进入服务类。
这是代码示例:
@WebAppConfiguration
@RunWith(SpringRunner.class)
@ContextConfiguration(classes = {AppplicationConfiguration.class})
public class ExternalControllerTest {
private MockMvc mockMvc;
@InjectMocks
private MyController myController;
@MockBean
myService myService;
@Before
public void setUp() throws Exception {
MockitoAnnotations.initMocks(this);
mockMvc = MockMvcBuilders
.standaloneSetup(myController)
.build();
}
@Test
public void testListCluster() throws Exception {
Input emrInput = new Input();
emrInput.setId("200004773");
emrInput.setName("test");
String expected = "{\"status\":\"Success\",\"message\":\"Success\",\"data\":\"somevalue\"}";
AutomateRestResponse response = new AutomateRestResponse<JsonObject>();
response.setMessage("Success");
response.setStatus("Success");
response.setData("somevalue");
Mockito.when(
externalService.listCluster(emrInput)
).thenReturn(response);
mockMvc.perform(post("/v1/gerData"))
.andExpect(status().isOk())
.andExpect(jsonPath("$.status", is("Success")));
verify(externalService, times(1)).listCluster(emrInput);
RequestBuilder requestBuilder = MockMvcRequestBuilders
.post("/v4/listCluster")
.accept(MediaType.APPLICATION_JSON).content(emrInputJosn)
.contentType(MediaType.APPLICATION_JSON);
MvcResult result = mockMvc.perform(requestBuilder).andReturn();
System.out.println("response body1" + result.getResponse()
.getContentAsString());
}`
请帮帮我。
【问题讨论】:
-
您正在尝试为哪个层创建测试?
-
请在您的帖子中添加minimal reproducible example。
-
你可以尝试用
@RunWith(MockitoJUnitRunner.class)替换@RunWith(SpringJUnit4ClassRunner.class)
标签: spring-boot junit