【发布时间】:2015-08-31 02:41:21
【问题描述】:
我正在尝试为 SpringBoot MVC REST 应用程序编写测试用例。我能够成功运行测试用例。但是当我试图模拟其中一种方法时,它不起作用。 测试用例仍然调用原始实现。
测试类:-
@RunWith(SpringJUnit4ClassRunner.class)
@SpringApplicationConfiguration(classes = { Initializer.class,
WebConfig.class })
@WebAppConfiguration
public class SampleControllerTest {
@Mock
CounterUtil counterUtil;
@InjectMocks
PreProcessor preProcessor
@Autowired
private WebApplicationContext context;
private static boolean isSetup = false;
@Test
public void sampleTest() {
org.mockito.Mockito.when(
counterUtil
.getCounter()).thenReturn(
"2222");
given().contentType("application/json").when()
.get("/initialize").then()
.statusCode(HttpServletResponse.SC_OK);
}
@Before
public void setUp() {
RestAssured.useRelaxedHTTPSValidation();
counterUtil = (CounterUtil) context
.getBean("counterUtil");
MockitoAnnotations.initMocks(this);
RestAssuredMockMvc.mockMvc = MockMvcBuilders.webAppContextSetup(context).build();
}
}
PreProcessor 是一个 concreate 类,具有 CounterUtil 的实例。
@Component
public class PreProcessor {
@Autowired
private CounterUtil counterUtil
public void myMethod(){
counterUtil.getCounter();
}
}
这些是 pom.xml 中的依赖项。
<!-- test dependencies -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.11</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-core</artifactId>
<version>2.5.3</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.5.3</version>
</dependency>
<dependency>
<groupId>org.mockito</groupId>
<artifactId>mockito-core</artifactId>
<version>1.9.0</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.hamcrest</groupId>
<artifactId>hamcrest-core</artifactId>
<version>1.3</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>com.jayway.restassured</groupId>
<artifactId>spring-mock-mvc</artifactId>
<version>2.4.1</version>
<scope>test</scope>
</dependency>
没有收到任何错误。执行工作正常,但不考虑模拟实现。
也欢迎任何建议或指点。
【问题讨论】:
-
我怀疑它与测试运行器 @RunWith(SpringJUnit4ClassRunner.class)
-
感谢您的回复。作为一个用于集成测试的 SpringMVC 项目,我无法提供任何其他测试运行器。
-
也许可以试试 MockitoAnnotations.initMocks(this)
-
谢谢。 MockitoAnnotations.initMocks(this) 被添加到@Before 方法中。
标签: java spring junit spring-boot mockito