我正在寻找一种简化以下代码的方法.
@WebAppConfiguration
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = {
// My configuration classes
})
public class MyServiceTest {
@Autowired
private MyService service;
@Test
public void myTest() {
Assert.assertTrue(service != null);
}
}
Run Code Online (Sandbox Code Playgroud)
我有很多配置类,我不想把它们放到每个测试类中.所以我有了创建自己的注释的想法:
@WebAppConfiguration
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = {
// My configuration classes
})
public @interface IntegrationTests {
}
Run Code Online (Sandbox Code Playgroud)
我尝试以下列方式使用它:
@IntegrationTests
public class MyServiceTest {
@Autowired
private MyService service;
@Test
public void myTest() {
Assert.assertTrue(service != null);
}
}
Run Code Online (Sandbox Code Playgroud)
但它不起作用.任何的想法?
我使用以下依赖项:
apply plugin: 'java'
apply plugin: 'eclipse'
apply plugin: 'idea'
apply plugin: 'spring-boot'
apply plugin: 'war'
compile("com.caucho:resin-hessian:4.0.23")
compile("mysql:mysql-connector-java")
compile('org.springframework.boot:spring-boot-starter-web:1.2.0.RELEASE')
compile("org.springframework.boot:spring-boot-starter-batch:1.2.0.RELEASE")
compile("org.springframework.boot:spring-boot-starter-actuator")
compile("javax.inject:javax.inject:1")
compile('org.springframework.batch:spring-batch-admin-manager:1.3.0.RELEASE') {
exclude module: 'slf4j-log4j12'
}
//SI
compile("org.springframework.integration:spring-integration-core:$springIntegrationVersion")
testCompile('org.springframework.boot:spring-boot-starter-test:1.2.0.RELEASE')
Run Code Online (Sandbox Code Playgroud)
创建了新的测试类:
@RunWith(SpringJUnit4ClassRunner.class)
@SpringApplicationConfiguration(classes = Application.class)
@WebAppConfiguration
@IntegrationTest
@ContextConfiguration(locations={"classpath:**/*.xml"})
@ComponentScan({"com.mycompany.notification.processor.service"})
public class DownloadFileTaskletTest {
@Autowired
private DownloadFileTasklet downloadFileTasklet;
@Test
public void execute()
{
System.out.printf("test123");
}
}
Run Code Online (Sandbox Code Playgroud)
我在Spring boot中创建了测试用例但是我得到了这个错误:
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'batch.DownloadFileTaskletTest': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: private com.mycompany.notification.processor.service.batch.tasks.DownloadFileTasklet …
Run Code Online (Sandbox Code Playgroud) 这是我的spring-boot应用程序的DbConfig。
@Configuration
@EnableTransactionManagement
public class DBConfig
{
@Bean
public LocalSessionFactoryBean sessionFactory()
{
....
}
@Bean
public DataSource aaDataSource()
{
.....
}
public PlatformTransactionManager transactionManager()
{
....
}
private Properties hibernateProperties()
{
....
}
}
Run Code Online (Sandbox Code Playgroud)
这是我的考试课
@RunWith(SpringJUnit4ClassRunner.class)
@SpringApplicationConfiguration(classes = Application.class)
@WebAppConfiguration
public class ApplicationTests {
@Test
public void contextLoads() {
}
}
Run Code Online (Sandbox Code Playgroud)
它是一个摇篮项目。当我在gradlew clean build
本地运行时,由于我的application.properties中的连接设置与我的sql连接匹配,因此构建成功。
但是,当我在我们的qa环境(数据库为qa one)中从jenkins box运行时,构建失败并出现以下异常。
java.lang.IllegalStateException: Failed to load ApplicationContext
....
Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'entityManagerFactory' defined in class path resource [org/springframework/boot/autoconfigure/orm/jpa/HibernateJpaAutoConfiguration.class]: …
Run Code Online (Sandbox Code Playgroud) 我正在尝试使用以下代码模拟发布请求。
我正在测试Spring Security登录请求。
MockMvc mvc = MockMvcBuilders.webAppContextSetup(context).addFilter(springSecurityFilterChain)
.apply(springSecurity())
.build();
MvcResult mvcResult = mvc.perform(post("/j_spring_security_check?api=true").param("userName", USERNAME)
.param("password", PASSWORD)).andReturn();
Run Code Online (Sandbox Code Playgroud)
代码工作正常,成功登录后,我将重定向到另一个控制器。
@Override
public void onAuthenticationSuccess(HttpServletRequest request,
HttpServletResponse response, Authentication authentication) throws IOException,
ServletException {
RequestDispatcher rd = request.getRequestDispatcher("/myURL");
rd.forward(request, response);
}
Run Code Online (Sandbox Code Playgroud)
当我运行测试时,我得到以下日志。重定向不会发生,并且映射到/ myURL的控制器不会被调用。
11:59:55.839 [main] DEBUG o.s.mock.web.MockRequestDispatcher - MockRequestDispatcher: forwarding to [/myURL]
11:59:55.841 [main] DEBUG o.s.s.w.c.HttpSessionSecurityContextRepository - The HttpSession is currently null, and the HttpSessionSecurityContextRepository is prohibited from creating an HttpSession (because the allowSessionCreation property is false) - SecurityContext thus not stored for next …
Run Code Online (Sandbox Code Playgroud) 我@PostConstruct
习惯在运行测试之前进行一些初始设置,但似乎该@PostConstruct
方法在每个测试上都运行,而不是在初始化测试类后才运行一次。我还看到构造函数在之前的每个测试之前被调用@PostConstruct
。为什么在每个@Test方法上初始化测试类,而不是一次初始化?
我在用 spring-boot-starter-test:1.5.7.RELEASE
样本测试设置:
@RunWith(SpringRunner.class)
public class TestClass {
public TestClass() {
System.out.println("constructor");
}
@PostConstruct
public void setup() {
System.out.println("setting up");
}
@Test
public void test1() {
System.out.println("test 1");
}
@Test
public void test2() {
System.out.println("test 2");
}
}
Run Code Online (Sandbox Code Playgroud)
在输出中,“构造函数”被打印两次,而“设置”被打印两次。“测试1”和“测试2”分别打印一次。
我们正与同事争论这种方法.他们说只在集成或功能级别上使用SpringRunner.
问题是在下面的级别使用它的利弊是什么?
例如,我有简单的bean:
public class RewardDurationCalculator {
private Clock clock;
public OptionalLong calculate(DurationType durationType, List<Pass> passes) {
long now = Instant.now(clock).getEpochSecond();
switch (durationType) {
case FULL_PASS:
return getCurrentPassDuration(passes, now);
case TILL_THE_END_OF_THE_CURRENT_ACTIVE_PASS:
return getTimeInCurrentPassLeft(passes, now);
}
return OptionalLong.empty();
}
private OptionalLong getCurrentPassDuration(List<Pass> passes, long now) {
return passes.stream()
.filter(currentPass(now))
.mapToLong(Pass::getDuration)
.findFirst();
}
private OptionalLong getTimeInCurrentPassLeft(List<Pass> passes, long now) {
return passes.stream()
.filter(currentPass(now))
.mapToLong(pass -> getEndTs(pass) - now)
.findFirst();
}
private Predicate<Pass> currentPass(long now) {
return pass -> pass.getStartTs() >= now && …
Run Code Online (Sandbox Code Playgroud) 我有一个Spring Boot Rest API,我一直在工作,上周我添加了Swagger和Swagger-UI.之后,存储库的测试(仅与存储库相关的测试)开始不起作用,当我运行它时,我收到此错误:
java.lang.IllegalStateException: Failed to load ApplicationContext
at org.springframework.test.context.cache.DefaultCacheAwareContextLoaderDelegate.loadContext(DefaultCacheAwareContextLoaderDelegate.java:124)
at org.springframework.test.context.support.DefaultTestContext.getApplicationContext(DefaultTestContext.java:83)
at org.springframework.test.context.support.DependencyInjectionTestExecutionListener.injectDependencies(DependencyInjectionTestExecutionListener.java:117)
at org.springframework.test.context.support.DependencyInjectionTestExecutionListener.prepareTestInstance(DependencyInjectionTestExecutionListener.java:83)
at org.springframework.boot.test.autoconfigure.SpringBootDependencyInjectionTestExecutionListener.prepareTestInstance(SpringBootDependencyInjectionTestExecutionListener.java:44)
at org.springframework.test.context.TestContextManager.prepareTestInstance(TestContextManager.java:230)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.createTest(SpringJUnit4ClassRunner.java:228)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner$1.runReflectiveCall(SpringJUnit4ClassRunner.java:287)
at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.methodBlock(SpringJUnit4ClassRunner.java:289)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:247)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:94)
at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290)
at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71)
at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288)
at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58)
at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268)
at org.springframework.test.context.junit4.statements.RunBeforeTestClassCallbacks.evaluate(RunBeforeTestClassCallbacks.java:61)
at org.springframework.test.context.junit4.statements.RunAfterTestClassCallbacks.evaluate(RunAfterTestClassCallbacks.java:70)
at org.junit.runners.ParentRunner.run(ParentRunner.java:363)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.run(SpringJUnit4ClassRunner.java:191)
at org.junit.runners.Suite.runChild(Suite.java:128)
at org.junit.runners.Suite.runChild(Suite.java:27)
at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290)
at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71)
at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288)
at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58)
at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268)
at org.junit.runners.ParentRunner.run(ParentRunner.java:363)
at org.junit.runner.JUnitCore.run(JUnitCore.java:137)
at com.intellij.junit4.JUnit4IdeaTestRunner.startRunnerWithArgs(JUnit4IdeaTestRunner.java:68)
at com.intellij.rt.execution.junit.IdeaTestRunner$Repeater.startRunnerWithArgs(IdeaTestRunner.java:51)
at com.intellij.rt.execution.junit.JUnitStarter.prepareStreamsAndStart(JUnitStarter.java:242)
at com.intellij.rt.execution.junit.JUnitStarter.main(JUnitStarter.java:70)
Caused by: org.springframework.beans.factory.UnsatisfiedDependencyException: …
Run Code Online (Sandbox Code Playgroud) 我已经创建了一个用于创建新用户的测试:
private static String USERS_ENDPOINT = "http://localhost:8080/users/";
private static String GROUPS_ENDPOINT = "http://localhost:8080/groups/";
@Test
@DirtiesContext(classMode = ClassMode.BEFORE_EACH_TEST_METHOD)
public void whenCreateAppUser() {
AppUser appUser = new AppUser();
appUser.setUsername("test@example.com");
appUser.setPassword("password");
// Throws java.net.HttpRetryException
template.postForEntity(USERS_ENDPOINT, appUser, AppUser.class);
ResponseEntity<AppUser> appUserResponse = template.getForEntity(USERS_ENDPOINT + "1/", AppUser.class);
assertEquals("Username is incorrect. AppUser not created?",
appUser.getUsername(), appUserResponse.getBody().getUsername());
}
Run Code Online (Sandbox Code Playgroud)
但是,由于某种原因,我得到了:
Caused by: java.net.HttpRetryException: cannot retry due to server authentication, in streaming mode
at sun.net.www.protocol.http.HttpURLConnection.getInputStream0(HttpURLConnection.java:1692)
at sun.net.www.protocol.http.HttpURLConnection.getInputStream(HttpURLConnection.java:1492)
at java.net.HttpURLConnection.getResponseCode(HttpURLConnection.java:480)
at org.springframework.http.client.SimpleClientHttpResponse.getRawStatusCode(SimpleClientHttpResponse.java:55)
at org.springframework.web.client.DefaultResponseErrorHandler.hasError(DefaultResponseErrorHandler.java:49)
at org.springframework.web.client.RestTemplate.handleResponse(RestTemplate.java:735)
at org.springframework.web.client.RestTemplate.doExecute(RestTemplate.java:700)
... 34 more …
Run Code Online (Sandbox Code Playgroud) 让我们以以下为例。
@Autowired
@MockBean
private Foo foobar;
Run Code Online (Sandbox Code Playgroud)
Spring Context是否Foo
先加载类,然后再应用模拟?还是@Mockbean
以某种方式检测到该获取,然后Spring创建并应用该模拟,而不是将类加载Foo
到Spring Context中。我怀疑是后者,但我想确认一下。
我想从json响应中撤消一个值,以便在我的其余测试用例中使用,这是我现在正在做的事情:
MvcResult mvcResult = super.mockMvc.perform(get("url").accept(MediaType.APPLICATION_JSON).headers(basicAuthHeaders()))
.andExpect(status().isOk())
.andExpect(jsonPath("$[0].id", is(6))).andReturn();
String responseAsString = mvcResult.getResponse().getContentAsString();
ObjectMapper objectMapper = new ObjectMapper(); // com.fasterxml.jackson.databind.ObjectMapper
MyResponse myResponse = objectMapper.readValue(responseAsString, MyResponse.class);
if(myResponse.getName().equals("name")) {
//
//
}
Run Code Online (Sandbox Code Playgroud)
我想知道是否有一种更优雅的方法可以直接从中检索值,MvcResult
例如jsonPath
进行匹配?
spring-test ×10
spring ×6
spring-boot ×5
spring-mvc ×4
java ×3
springrunner ×2
annotations ×1
gradle ×1
swagger ×1
swagger-2.0 ×1
testing ×1
unit-testing ×1