如何为这种方法编写junit测试用例?

时间:2021-05-18 22:14:16

Here is my method.

这是我的方法。

@Path("/")
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
public class XYZ {
    @GET
    @Path("/workflow")
    public Response getWorkflowsData() {    
        Object output=new Object();
        return Response.ok().entity(output).build();
        // or defination
    }
}

I am trying to do like this.

我想这样做。

@Test
public void getWorkflowsDataTest() throws Exception{
     MvcResult result = mockMvc
            .perform(MockMvcRequestBuilders.get("/workflow")).andReturn();
     String finalresult= result.getResponse().getContentAsString();
     assertEquals(200, result.getResponse().getStatus());
}

by this I am not able to go to the actual method.

通过这个我不能去实际的方法。

1 个解决方案

#1


1  

Since you are using MockMvcRequestBuilders, your test class should have @SpringJUnit4ClassRunner annotation, as well as @ContextConfiguration should be specified:

由于您使用的是MockMvcRequestBuilders,因此您的测试类应该具有@SpringJUnit4ClassRunner注释,并且应该指定@ContextConfiguration:

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = {YOUR_CONTEXT_CLASS_GOES_HERE.class})
@WebAppConfiguration
public class MyTestClass {

     @Resource
     private WebApplicationContext webApplicationContext;

     private MockMvc mockMvc;

     @Before
     public void setup() {
         this.mockMvc = MockMvcBuilders.webAppContextSetup(this.webApplicationContext).build();
     }

     @Test
     public void getWorkflowsDataTest() throws Exception{
         MvcResult result = mockMvc
            .perform(MockMvcRequestBuilders.get("/workflow")).andReturn();
         String finalresult= result.getResponse().getContentAsString();
         assertEquals(200, result.getResponse().getStatus());
    }
}

#1


1  

Since you are using MockMvcRequestBuilders, your test class should have @SpringJUnit4ClassRunner annotation, as well as @ContextConfiguration should be specified:

由于您使用的是MockMvcRequestBuilders,因此您的测试类应该具有@SpringJUnit4ClassRunner注释,并且应该指定@ContextConfiguration:

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = {YOUR_CONTEXT_CLASS_GOES_HERE.class})
@WebAppConfiguration
public class MyTestClass {

     @Resource
     private WebApplicationContext webApplicationContext;

     private MockMvc mockMvc;

     @Before
     public void setup() {
         this.mockMvc = MockMvcBuilders.webAppContextSetup(this.webApplicationContext).build();
     }

     @Test
     public void getWorkflowsDataTest() throws Exception{
         MvcResult result = mockMvc
            .perform(MockMvcRequestBuilders.get("/workflow")).andReturn();
         String finalresult= result.getResponse().getContentAsString();
         assertEquals(200, result.getResponse().getStatus());
    }
}