控制器中的异常未在junit

时间:2018-05-07 12:30:02

标签: java junit mockito

我有一个控制器类,它是这样的:

@Controller
public class ExampleController
{
   @RequestMapping(value = "/samplePage")
   public ResponseEntity getSampleDetails()
   {

       SomeClass Obj = new SomeClass()
    try{
        response = Obj.getData();
        return new ResponseEntity<>(response,HttpStatus.Ok)
       }
    catch(IllegalArgumentException e)
      {
        return new ResponseEntity<>(HttpStatus.INTERNAL_SERVER_ERROR);
      }
   }
}

我想编写一个junit测试用例,在调用someClass.getData时测试非法的ArgumentException.Hence我使用Mockito抛出异常。

 @RunWith(PowerMockRunner.class)
    public class exampleControllerTest
    {
    @Mock
    private SomeClass someClass;
    @InjectMocks
    private ExampleController exampleController;
    @Before
    public void before()
        {
         exampleControllerMockMvc = MockMvcBuilders.standaloneSetup(exampleController).build();
        }

    @Test
    public void exampleControllerTest_IllegalArgumentException_throwsInternalException()
        exampleControllerMockMvc.perform(get("/samplePage")).andExpect(status().is5xxServerError);
     Mockito.doThrow(new IllegalArgumentException).when(someClass).getData()
    }

然而,当我运行代码时,我收到一条错误说明

预期响应状态值200的范围:SERVER_ERROR但是:SUCCESSFUL。

如何测试异常?

2 个答案:

答案 0 :(得分:0)

您的问题是您在实际调用被测单元(您的控制器)后正在设置模拟器。您应首先设置模拟并执行调用:

Mockito.doThrow(new IllegalArgumentException()).when(someClass).getData();
exampleControllerMockMvc.perform(get("/samplePage")).andExpect(status().is5xxServerError);

答案 1 :(得分:0)

您的代码中存在多个问题。

  1. 您没有模仿构造函数调用SomeClass Obj = new SomeClass(); SomeClass字段@Mock覆盖它不能完成这项工作。此地点需要PowerMock

    PowerMockito.whenNew(SomeClass.class).withNoArguments().thenReturn(someClass);
    
  2. 应该模拟特定方法getData()以抛出异常,但在执行完全测试请求之前

    Mockito.doThrow(new IllegalArgumentException()).when(someClass).getData();
    
  3. 要让PowerMock增强课程,您需要课程级别@PrepareForTest(ExampleController.class)

  4. 按照惯例,类从大写字母开始命名,因此exampleControllerTest - &gt; ExampleControllerTest

  5. 把所有的东西放在一起

    @RunWith(PowerMockRunner.class)
    @PrepareForTest(ExampleController.class)
    public class ExampleControllerTest
    {
        private SomeClass someClass;
        private MockMvc exampleControllerMockMvc;
    
        @Before
        public void before() {
            someClass = Mockito.mock(SomeClass.class);
            PowerMockito.whenNew(SomeClass.class).withNoArguments().thenReturn(someClass);
            exampleControllerMockMvc = MockMvcBuilders.standaloneSetup(new ExampleController())
                                                      .build();
        }
    
        @Test
        public void exampleControllerTest_IllegalArgumentException_throwsInternalException() {
            Mockito.doThrow(new IllegalArgumentException).when(someClass).getData();
            exampleControllerMockMvc.perform(get("/samplePage"))
                                    .andExpect(status().is5xxServerError);  
        }
    }
    

    希望它有所帮助!