我正在为我的Spring控制器编写JUnits。在其中一个案例中,我正在测试控制器中的Exception
catch
ed。我已经模拟了抛出RuntimeException的服务。其他测试检查成功输出。
单独两个测试都有效,但是当我同时执行两个测试时,如果第一个测试先执行,那么第二个测试也会抛出RuntimeException。我需要取消注册模拟方法吗?
(请忽略语法)
class UserController {
@Autowired
UserService service;
@RequestMapping("...")
public ResponseEntity getUser(){
try{
User user = service.getUserAttributes();
return new ResponseEntity(user, HttpStatus.OK);
}
catch(Exception e){
return new ResponseEntity("Eror", HttpStatus.BAD_REQUEST);
}
}
}
@RunWith(SpringJUnit4ClassRunner.class)
@WebAppConfiguration
@ContextConfiguration(classes=TestConfig.class)
public class UserControllerDocumentation {
@Autowired
private WebApplicationContext webApplicationContext;
private RestDocumentationResultHandler document;
private MockMvc mockMvc;
@Rule
public final RestDocumentation restDocumentation = new RestDocumentation("target/generated-snippets");
@Autowired
UserService userService;
@Before
public void setUp(){
this.document = document("{method-name}", preprocessRequest(prettyPrint()),
preprocessResponse(prettyPrint()));
this.mockMvc = MockMvcBuilders.webAppContextSetup(this.webApplicationContext)
.apply(documentationConfiguration(this.restDocumentation)).alwaysDo(document)
.build();
}
@Test
public void textError() throws Exception {
when(userService.getUserAttributes(anyInt())).thenThrow(new RuntimeException());
this.mockMvc.perform(get("/user/xxx")
.accept("application/xml"))
.andExpect(status().isBadRequest());
}
@Test
public void textUser() throws Exception {
when(userService.getUserAttributes(anyInt())).thenReturn(mockUserObj);
this.mockMvc.perform(get("/user/10")
.accept("application/xml"))
.andExpect(status().isOk());
}
答案 0 :(得分:0)
我不知道@Autowired是如何运作的,但很明显:你的班级有一个userService
的实例;并且你的textError()测试用例配置为抛出异常。当你的第二次测试运行时,那个“行为规范”仍然存在并投向你。
因此,我看到两个选择:
a)您使用“after”或“before”方法重置userService
b)每个测试方法都有自己的userService
答案 1 :(得分:0)
也许你应该在运行每个测试之前重置模拟对象。 你可以使用重置方法来做到这一点。
以下是更多详情 http://site.mockito.org/mockito/docs/current/org/mockito/Mockito.html#17
要在每个课程之前运行此课程,您可以使用@Before
注释。
答案 2 :(得分:0)
事实证明,即使抛出异常,我也需要为mocked方法返回一些内容。在public class GvData
{
public string stat { get; set; }
public int EMP_ID { get; set; }
public int Train_ID { get; set; }
}
public partial class GridViewConditionalButtons : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if(!Page.IsPostBack)
{
var g1 = new GvData { stat = "S2", Train_ID = 1, EMP_ID = 1 };
var g2 = new GvData { stat = "S2", Train_ID = 2, EMP_ID = 2 };
var g3 = new GvData { stat = "S1", Train_ID = 3, EMP_ID = 3 };
GridView1.DataSource = new List<GvData> { g1, g2, g3 };
GridView1.DataBind();
}
}
}
thenReturn(null)
thenThrow