【发布时间】:2016-06-02 12:17:06
【问题描述】:
我使用 Mockito 为 JUnit 编写了一个工作测试,并尝试使其适应 TestNG,但奇怪的是,使用 TestNG 只有一个测试可以工作。
我认为这在某种程度上与模拟的重置有关,但我尝试调用 Mockito.reset 并使用 BeforeMethod 和 BeforeClass 以及不同的组合,但仍然只能通过一个测试。
我需要做什么才能使测试正常进行?
@BeforeClass
public void setUp() {
MockitoAnnotations.initMocks(this);
mockMvc = MockMvcBuilders.standaloneSetup(calculatorController).build();
}
@AfterMethod
public void reset() {
Mockito.reset(calculatorService);
}
@Test
public void addFunctionTest() throws Exception {
Assert.assertNotNull(calculatorController);
Result expectedResult = new Result();
expectedResult.setResult(10);
when(calculatorService.add(anyInt(), anyInt())).thenReturn(expectedResult);
mockMvc.perform(get("/calculator/add").accept(MediaType.APPLICATION_JSON_VALUE)
.param("val1", "100")
.param("val2", "100"))
.andExpect(content().contentType("application/json"))
.andExpect(status().isOk())
.andExpect(jsonPath("$.result", equalTo(10)));
verify(calculatorService, times(1)).add(anyInt(), anyInt());
}
@Test
public void subtractFunctionTest() throws Exception {
Assert.assertNotNull(calculatorController);
Result expectedResult = new Result();
expectedResult.setResult(90);
when(calculatorService.subtract(anyInt(), anyInt())).thenReturn(expectedResult);
mockMvc.perform(get("/calculator/subtract").accept(MediaType.APPLICATION_JSON_VALUE)
.param("val1", "100")
.param("val2", "10"))
.andExpect(content().contentType("application/json"))
.andExpect(status().isOk())
.andExpect(jsonPath("$.result", equalTo(90)));
verify(calculatorService, times(1)).subtract(anyInt(), anyInt());
}
第二个测试似乎总是在断言内容类型未设置或预期结果错误时失败。
似乎第一个测试的响应在第二个测试中以某种方式被评估,因此显然是错误的!
我知道控制器和服务按预期工作,使用 jUnit 运行的完全相同的测试实际上可以正常工作。
只有当我执行以下操作时,我才能使测试正常执行:
@BeforeGroups("subtract")
public void reset() {
Mockito.reset(calculatorService);
mockMvc = MockMvcBuilders.standaloneSetup(calculatorController).build();
}
@Test(groups = "subtract")
public void subtractFunctionTest() throws Exception {
System.out.println("***** IN METHOD *****");
Assert.assertNotNull(calculatorController);
Result expectedResult = new Result();
expectedResult.setResult(90);
when(calculatorService.subtract(anyInt(), anyInt())).thenReturn(expectedResult);
//Perform HTTP Get for the homepage
mockMvc.perform(get("/calculator/subtract").accept(MediaType.APPLICATION_JSON_VALUE)
.param("val1", "100")
.param("val2", "10"))
.andExpect(content().contentType("application/json"))
.andExpect(status().isOk())
.andExpect(jsonPath("$.result", equalTo(90)));
//Verify that the service method was only called one time
verify(calculatorService, times(1)).subtract(anyInt(), anyInt());
}
这意味着我需要为每个测试方法添加这些重置方法之一,然后我需要为每个测试方法设置一个组,这似乎不正确。
【问题讨论】:
-
您使用什么库进行断言 (
Result expectedResult = new Result())? -
你在每个方法之后都重置了模拟,但你没有对
mocMvc做任何事情。这会影响你的测试吗?您能否通过将@BeforeClass更改为@BeforeMethod来验证这一点 -
嗨,Eugen,我试过玩,但没有任何组合奏效。我将用我设法开始工作的内容更新我的帖子,但这意味着很多代码重复。
-
库是springs MockMvcResultMatchers
标签: spring unit-testing mockito testng