我正在使用JUnit来测试我的Spring MVC控制器.下面是我的方法,它返回一个index.jsp页面并Hello World在屏幕上显示 -
@RequestMapping(value = "index", method = RequestMethod.GET)
public HashMap<String, String> handleRequest() {
HashMap<String, String> model = new HashMap<String, String>();
String name = "Hello World";
model.put("greeting", name);
return model;
}
Run Code Online (Sandbox Code Playgroud)
以下是我对上述方法的JUnit测试:
public class ControllerTest {
private MockMvc mockMvc;
@Before
public void setup() throws Exception {
InternalResourceViewResolver viewResolver = new InternalResourceViewResolver();
viewResolver.setPrefix("/WEB-INF/views/");
viewResolver.setSuffix(".jsp");
this.mockMvc = standaloneSetup(new Controller()).setViewResolvers(viewResolver).build();
}
@Test
public void test01_Index() throws Exception {
mockMvc.perform(get("/index")).andExpect(status().isOk()).andExpect(content().contentType("application/json"))
.andExpect(jsonPath("$.greeting").value("Hello World"));
}
}
Run Code Online (Sandbox Code Playgroud)
当我调试它时,junit上面运行正常但是当我运行junit时run as junit,它给了我这个错误 …
我正在尝试使用spring security和一个简单的home(root)控制器在spring-boot中运行单元测试,该控制器使用百日咳进行模板处理.我正在尝试编写一些单元测试来验证我的安全权限是否正常工作以及正确的数据是否隐藏或显示在我的模板中(使用百万富翁弹簧安全集成).应用程序本身在运行时可以正常工作.我只是想验证它是否正在使用一组集成测试.您可以在此处找到所有代码,但我还将在下面包含相关的代码段:
https://github.com/azeckoski/lti_starter
Run Code Online (Sandbox Code Playgroud)
控制器非常简单,只能渲染模板(在根目录 - 即"/").
@Controller
public class HomeController extends BaseController {
@RequestMapping(method = RequestMethod.GET)
public String index(HttpServletRequest req, Principal principal, Model model) {
log.info("HOME: " + req);
model.addAttribute("name", "HOME");
return "home"; // name of the template
}
}
Run Code Online (Sandbox Code Playgroud)
模板中有很多,但测试的相关位是:
<p>Hello Spring Boot User <span th:text="${username}"/>! (<span th:text="${name}"/>)</p>
<div sec:authorize="hasRole('ROLE_USER')">
This content is only shown to users (ROLE_USER).
</div>
<div sec:authorize="isAnonymous()"><!-- only show this when user is NOT logged in -->
<h2>Form Login endpoint</h2>
...
</div>
Run Code Online (Sandbox Code Playgroud)
最后测试:
@RunWith(SpringJUnit4ClassRunner.class)
@SpringApplicationConfiguration(classes …Run Code Online (Sandbox Code Playgroud) spring-mvc spring-security spring-test-mvc thymeleaf spring-boot
在我正在研究的Java项目中,我为单元测试提供了以下设置:
@RunWith(SpringJUnit4ClassRunner.class)并@WebAppConfiguration运行单元测试,我创建了一个用于测试应用程序的MockMvc实例webAppContextSetup(webApplicationContext).hibernate.hbm2ddl.import_files属性以加载import.sql带有SQL语句的文件来填充(内存中)数据库.现在,我已经确认了以上所有这些工作:
import.sql各种测试证实,执行中的SQL语句.现在问题是:我添加的语句出现的错误import.sql似乎没有在任何地方报告,也没有任何迹象表明发生了错误.相反,后续语句根本不会执行.(我通过测试证实了这一点.)
有没有什么办法,或将这些错误的报道,我显然不知道的?这有额外的Hibernate属性吗?
摘自hibernate测试配置:
<bean id="sessionFactory" name="mySessionFactory" class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
<property name="dataSource" ref="myDataSource" />
<property name="hibernateProperties">
<props>
<prop key="hibernate.archive.autodetection">class,hbm</prop>
<prop key="hibernate.dialect">org.hibernate.dialect.HSQLDialect</prop>
<prop key="hibernate.show_sql">true</prop>
<prop key="hibernate.connection.driver_class">org.hsqldb.jdbcDriver</prop>
<prop key="hibernate.connection.username">sa</prop>
<prop key="hibernate.connection.password"></prop>
<prop key="hibernate.connection.url">jdbc:hsqldb:mem:myschema</prop>
<prop key="hibernate.hbm2ddl.auto">create</prop>
<prop key="hibernate.hbm2ddl.import_files">configuration/test/import.sql</prop>
<prop key="hibernate.hbm2ddl.import_files_sql_extractor">org.hibernate.tool.hbm2ddl.MultipleLinesSqlCommandExtractor</prop>
<!-- when using type="yes_no" for booleans, the line below allow booleans in HQL expressions: -->
<prop key="hibernate.query.substitutions">true 'Y', …Run Code Online (Sandbox Code Playgroud) 我正在使用spring-test-mvc测试我的控制器,但我找不到打印请求体的方法,这非常不方便.
与MockMvcResultHandlers.print()
mvc.perform(put("/payment/1234")
.content("{\"amount\":2.3")
.contentType(MediaType.APPLICATION_JSON))
.andDo(print());
Run Code Online (Sandbox Code Playgroud)
我找到了一些身体信息,但没有找到身体部位:
MockHttpServletRequest:
HTTP Method = PUT
Request URI = /payment/1234
Parameters = {}
Headers = {Content-Type=[application/json]}
Handler:
Type = com.restbucks.ordering.rest.PaymentResource
Method = public org.springframework.hateoas.Resource<com.restbucks.ordering.domain.Payment> com.restbucks.ordering.rest.PaymentResource.handle(com.restbucks.ordering.commands.MakePaymentCommand)
Async:
Async started = false
Async result = null
Run Code Online (Sandbox Code Playgroud)
更新
在阅读了一些源代码之后,似乎我应该扩展MockMvcResultHandlers来添加一些打印项目?
//PrintingResultHandler.java
protected void printRequest(MockHttpServletRequest request) throws Exception {
this.printer.printValue("HTTP Method", request.getMethod());
this.printer.printValue("Request URI", request.getRequestURI());
this.printer.printValue("Parameters", getParamsMultiValueMap(request));
this.printer.printValue("Headers", getRequestHeaders(request));
// add body print?
}
Run Code Online (Sandbox Code Playgroud)
更新 概念证明代码:
public static class CustomMockMvcResultHandlers {
public static ResultHandler print() {
return new ConsolePrintingResultHandler(); …Run Code Online (Sandbox Code Playgroud) 我正在尝试@WebMvcTest使用类中定义的自定义安全设置 进行测试SecurityConfig:
@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
http.authorizeRequests().antMatchers("/admin*").access("hasRole('ADMIN')").antMatchers("/**").permitAll().and().formLogin();
}
@Autowired
public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
auth.inMemoryAuthentication().withUser("user").password("password").roles("ADMIN");
}
}
Run Code Online (Sandbox Code Playgroud)
测试类是:
@RunWith(SpringRunner.class)
@WebMvcTest(value = ExampleController.class)
public class ExampleControllerMockMVCTest {
@Autowired
private MockMvc mockMvc;
@Test
public void indexTest() throws Exception {
mockMvc.perform(get("/"))
.andExpect(status().isOk())
.andExpect(view().name("index"));
}
@Test
public void adminTestWithoutAuthentication() throws Exception {
mockMvc.perform(get("/admin"))
.andExpect(status().is3xxRedirection()); //login form redirect
}
@Test
@WithMockUser(username="example", password="password", roles={"ANONYMOUS"})
public void adminTestWithBadAuthentication() throws …Run Code Online (Sandbox Code Playgroud) 我在我的 java 配置中定义了消息源:
@Bean(name = "messageSource")
public MessageSource messageSource() {
ResourceBundleMessageSource messageSource = new ResourceBundleMessageSource();
messageSource.setBasenames(
"/i18n/ir/kia/industry/webapp/entity",
"/i18n/ir/kia/industry/webapp/formErrors",
"/i18n/ir/kia/industry/webapp/frontend",
"/i18n/ir/kia/industry/webapp/frontendPages");
return messageSource;
}
Run Code Online (Sandbox Code Playgroud)
当使用站点和消息正确显示时它工作正常,但是当尝试使用以下内容编写 spring 测试时:
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = {TestContext.class, SpringMVC.class})
@WebAppConfiguration
public abstract class AbstractTestClass {
protected MockMvc mockMvc;
@Autowired
private WebApplicationContext webApplicationContext;
@Before
public void setUp() throws Exception {
mockMvc = MockMvcBuilders.webAppContextSetup(webApplicationContext).build();
}
}
Run Code Online (Sandbox Code Playgroud)
和一个简单地扩展它的测试类,我得到错误Can't find bundle for base name /i18n/ir/kia/industry/webapp/entity。
它在启动 tomcat 并在 jsp 文件中使用消息源时工作正常,但在测试时没有运气。我曾尝试在 WEB-INF 下移动 i18n 文件夹,但它也没有帮助。
目标文件夹看起来像这样,请不要告诉我将 i18n 文件夹添加到目标资源...

我使用的junit 4.12, jmockit 1.19与spring-test 4.1.1.RELEASE测试我的Spring MVC的Java项目.
我的这些依赖关系的顺序pom.xml:
jmockitjunitspring-test服务层的测试用例工作正常.我只使用spring-test来测试控制器.在测试控制器时,我收到以下错误:
java.lang.IllegalStateException:JMockit未正确初始化; 请确保jmockit在运行时类路径中的junit之前,或者使用@RunWith(JMockit.class)
对于服务层,我通过使用@RunWith(JMockit.class )on test class 解决了这个错误.
但对于控制器我需要注释@RunWith(SpringJUnit4ClassRunner.class ).
如何解决此错误?
注:我把jmockit之前junit在pom.xml
控制器
@RestController
@Validated
class MyController {
@GetMapping("/foo")
public String unwrapped(@Min(1) @RequestParam("param") int param) {
return Integer.toString(param);
}
@GetMapping("/bar")
public String wrapped(@ModelAttribute @Valid Wrapper bean) {
return Integer.toString(bean.param);
}
static class Wrapper {
@Min(1)
int param;
public void setParam(final int param) {
this.param = param;
}
}
}
Run Code Online (Sandbox Code Playgroud)
测试
public class MyControllerTest {
MyController controller = new MyController();
MockMvc mockMvc = MockMvcBuilders
.standaloneSetup(this.controller)
.build();
@Test // fails
public void unwrapped() throws Exception {
this.mockMvc.perform(get("/foo")
.param("param", "0"))
.andExpect(status().isBadRequest());
}
@Test // passes …Run Code Online (Sandbox Code Playgroud) 我有一个简单的网络应用程序:
@SpringBootApplication
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}
@RestController
public class SimpleController {
@Autowired
private String sayHello;
@GetMapping("/hello")
public String hello() {
return sayHello;
}
}
@Configuration
public class StringConfig {
@Bean
public String sayHelloWorld() {
return "Hello, World!";
}
}
Run Code Online (Sandbox Code Playgroud)
并添加测试:
//This is abstarct class for test.
@WebAppConfiguration
@RunWith(SpringRunner.class)
@ContextConfiguration(classes = Application.class)
public abstract class AbstractTestClass {
@Autowired
private WebApplicationContext webApplicationContext;
protected MockMvc mockMvc;
@Before
public void init() {
mockMvc = …Run Code Online (Sandbox Code Playgroud) 我在尝试 Spock 并在编写控制器测试时遇到了一个有趣的问题。
WebMvcTest(value = SomeController.class)
@AutoConfigureMockMvc
@ActiveProfiles(value = "restapi")
@Import(value = SecurityConfiguration)
class AccountBalanceControllerTest extends Specification {
@Autowired
SomeController someController
@MockBean
SomeService someService
def "lets test it" {
given:
someService.findAllByName(_) >> ["Some", "Work"]
when:
def response = mockMvc.perform(get("/v1/someName/545465?fast=false").with(user("mvc-test").roles("SOME_ACCOUNTS")))
then:
response.andExpect(status().isOk())
}
}
Run Code Online (Sandbox Code Playgroud)
所以问题是SomeService实例上的模拟方法不起作用,因为它使用不同的 Mock 类来模拟类的实例SomeService 。我在设置中使用来自 Spock 的静态 Mock 方法,然后使用 setterSomeService在控制器中设置。我的问题是有什么优雅的方法可以用于@MockBeanSpockSpecification测试。
spring-test-mvc ×10
java ×6
spring ×5
spring-boot ×5
spring-mvc ×3
spring-test ×3
junit ×2
hibernate ×1
hsqldb ×1
jmockit ×1
mockmvc ×1
spock ×1
testng ×1
thymeleaf ×1
unit-testing ×1