我有一个控制器类,它是这样的:
@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 测试用例来测试非法的 ArgumentException.因此,当调用 someClass.getData 时,我使用 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但为:成功。
如何测试异常?
代码中存在多个问题。
-
你不是在嘲笑构造函数调用
SomeClass Obj = new SomeClass();
SomeClass
字段,@Mock
它在这里不起作用。这个地方需要PowerMockPowerMockito.whenNew(SomeClass.class).withNoArguments().thenReturn(someClass);
-
在你应该模拟特定方法之后,
getData()
抛出异常,但在执行确切的测试请求之前Mockito.doThrow(new IllegalArgumentException()).when(someClass).getData();
-
要让 PowerMock 增强类,您需要在类级别进行
@PrepareForTest(ExampleController.class)
-
按照惯例,类从大写字母开始命名,因此
exampleControllerTest
->ExampleControllerTest
将所有事物整合在一起
@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);
}
}
希望对您有所帮助!
您的问题是您在实际调用被测单元(您的控制器)后设置模拟。您应该首先设置您的模型并执行呼叫:
Mockito.doThrow(new IllegalArgumentException()).when(someClass).getData();
exampleControllerMockMvc.perform(get("/samplePage")).andExpect(status().is5xxServerError);