为什么静态块未使用@Autowire注释进行初始化

时间:2017-12-31 07:45:57

标签: spring unit-testing autowired

无法使用 @Autowired 注释初始化类的静态块。但是能够使用 运算符对其进行初始化。如果@Mockbean的存在可以改变这里的事情,请原谅我的无知。我还需要了解更多。

使用@Component注释的服务类,这意味着@Autowired肯定会创建此类的实例。

@Component
public class StudentService {

private static List<Student> students = new ArrayList<>();

static {
    //Initialize Data
    Course course1 = new Course("Course1", "Spring", "10 Steps", Arrays
            .asList("Learn Maven", "Import Project", "First Example",
                    "Second Example"));
    Course course2 = new Course("Course2", "Spring MVC", "10 Examples",
            Arrays.asList("Learn Maven", "Import Project", "First Example",
                    "Second Example"));
    Course course3 = new Course("Course3", "Spring Boot", "6K Students",
            Arrays.asList("Learn Maven", "Learn Spring",
                    "Learn Spring MVC", "First Example", "Second Example"));
    Course course4 = new Course("Course4", "Maven",
            "Most popular maven course on internet!", Arrays.asList(
                    "Pom.xml", "Build Life Cycle", "Parent POM",
                    "Importing into Eclipse"));

    Student ranga = new Student("Student1", "Ranga Karanam",
            "Hiker, Programmer and Architect", new ArrayList<>(Arrays
                    .asList(course1, course2, course3, course4)));

    Student satish = new Student("Student2", "Satish T",
            "Hiker, Programmer and Architect", new ArrayList<>(Arrays
                    .asList(course1, course2, course3, course4)));

    students.add(ranga);
    students.add(satish);
}

/*public static void main(String[] args) {
    StudentService studentService = new StudentService();
    System.out.println("Students From Instance " + studentService.students);
    System.out.println("Returning student with ID Student1 From Instance " + studentService.retrieveStudent("Student1"));
    System.out.println(students);
}*/

public List<Student> retrieveAllStudents() {
    return students;
}

public Student retrieveStudent(String studentId) {
    for (Student student : students) {
        if (student.getId().equals(studentId)) {
            return student;
        }
    }
    return null;
}

学生班

public class Student {
private String id;
private String name;
private String description;
private List<Course> courses;

public Student(String id, String name, String description,
        List<Course> courses) {
    super();
    this.id = id;
    this.name = name;
    this.description = description;
    this.courses = courses;
}
//getter and setters

课程班

public class Course {
private String id;
private String name;
private String description;
private List<String> steps;

public Course() {

}

public Course(String id, String name, String description, List<String> steps) {
    super();
    this.id = id;
    this.name = name;
    this.description = description;
    this.steps = steps;
}
//getter and setters

使用@Autowired

测试课程和结果
@RunWith(SpringRunner.class)
@WebMvcTest(value = StudentController.class, secure = false)
public class StudentControllerTest {
@Autowired
private MockMvc mockMvc;

@MockBean
StudentService studentService;

@AutoWired
StudentService studentService1;

@Test
public void testSomething() {
    Student st1 = studentService1.retrieveStudent("Student2");
    assertNotNull(st1);
}

}

enter image description here

使用new运算符测试类和结果

@RunWith(SpringRunner.class)
@WebMvcTest(value = StudentController.class, secure = false)

public class StudentControllerTest {

@Autowired
private MockMvc mockMvc;

@MockBean
StudentService studentService;

StudentService studentService1 = new StudentService();

@Test
public void testSomething() {
    Student st1 = studentService1.retrieveStudent("Student2");
    assertNotNull(st1);
}

}

enter image description here

堆栈跟踪

[INFO] Scanning for projects...
[INFO]                                                                         
[INFO] ------------------------------------------------------------------------
[INFO] Building student-services 0.0.1-SNAPSHOT
[INFO] ------------------------------------------------------------------------
[INFO] 
[INFO] --- maven-resources-plugin:2.6:resources (default-resources) @ student-services ---
[INFO] Using 'UTF-8' encoding to copy filtered resources.
[INFO] Copying 1 resource
[INFO] Copying 0 resource
[INFO] 
[INFO] --- maven-compiler-plugin:3.1:compile (default-compile) @ student-services ---
[INFO] Changes detected - recompiling the module!
[INFO] Compiling 6 source files to /Users/tadtab/Documents/student-services/target/classes
[INFO] 
[INFO] --- maven-resources-plugin:2.6:testResources (default-testResources) @ student-services ---
[INFO] Using 'UTF-8' encoding to copy filtered resources.
[INFO] skip non existing resourceDirectory /Users/tadtab/Documents/student-services/src/test/resources
[INFO] 
[INFO] --- maven-compiler-plugin:3.1:testCompile (default-testCompile) @ student-services ---
[INFO] Nothing to compile - all classes are up to date
[INFO] 
[INFO] --- maven-surefire-plugin:2.18.1:test (default-test) @ student-services ---
[INFO] Surefire report directory: /Users/tadtab/Documents/student-services/target/surefire-reports

-------------------------------------------------------
 T E S T S
-------------------------------------------------------
ERROR StatusLogger No log4j2 configuration file found. Using default configuration: logging only errors to the console.
Running com.in28minutes.springboot.studentservices.StudentServicesApplicationTests

  .   ____          _            __ _ _
 /\\ / ___'_ __ _ _(_)_ __  __ _ \ \ \ \
( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \
 \\/  ___)| |_)| | | | | || (_| |  ) ) ) )
  '  |____| .__|_| |_|_| |_\__, | / / / /
 =========|_|==============|___/=/_/_/_/
 :: Spring Boot ::        (v1.4.4.RELEASE)

2017-12-31 03:19:23.644  INFO 15809 --- [           main] c.i.s.s.StudentServicesApplicationTests  : Starting StudentServicesApplicationTests on Tadeles-MacBook-Pro.local with PID 15809 (started by tadtab in /Users/tadtab/Documents/student-services)
2017-12-31 03:19:23.646  INFO 15809 --- [           main] c.i.s.s.StudentServicesApplicationTests  : No active profile set, falling back to default profiles: default
2017-12-31 03:19:24.090  INFO 15809 --- [           main] o.s.c.a.AnnotationUtils                  : Failed to introspect annotations on [class org.springframework.boot.actuate.autoconfigure.EndpointWebMvcHypermediaManagementContextConfiguration]: java.lang.ArrayStoreException: sun.reflect.annotation.TypeNotPresentExceptionProxy
2017-12-31 03:19:24.090  INFO 15809 --- [           main] o.s.c.a.AnnotationUtils                  : Failed to introspect annotations on [class org.springframework.boot.actuate.autoconfigure.EndpointWebMvcHypermediaManagementContextConfiguration]: java.lang.ArrayStoreException: sun.reflect.annotation.TypeNotPresentExceptionProxy
2017-12-31 03:19:25.389  INFO 15809 --- [           main] o.s.b.a.e.m.EndpointHandlerMapping       : Mapped "{[/configprops || /configprops.json],methods=[GET],produces=[application/json]}" onto public java.lang.Object org.springframework.boot.actuate.endpoint.mvc.EndpointMvcAdapter.invoke()
2017-12-31 03:19:25.390  INFO 15809 --- [           main] o.s.b.a.e.m.EndpointHandlerMapping       : Mapped "{[/metrics/{name:.*}],methods=[GET],produces=[application/json]}" onto public java.lang.Object org.springframework.boot.actuate.endpoint.mvc.MetricsMvcEndpoint.value(java.lang.String)
2017-12-31 03:19:25.390  INFO 15809 --- [           main] o.s.b.a.e.m.EndpointHandlerMapping       : Mapped "{[/metrics || /metrics.json],methods=[GET],produces=[application/json]}" onto public java.lang.Object org.springframework.boot.actuate.endpoint.mvc.EndpointMvcAdapter.invoke()
2017-12-31 03:19:25.391  INFO 15809 --- [           main] o.s.b.a.e.m.EndpointHandlerMapping       : Mapped "{[/mappings || /mappings.json],methods=[GET],produces=[application/json]}" onto public java.lang.Object org.springframework.boot.actuate.endpoint.mvc.EndpointMvcAdapter.invoke()
2017-12-31 03:19:25.392  INFO 15809 --- [           main] o.s.b.a.e.m.EndpointHandlerMapping       : Mapped "{[/trace || /trace.json],methods=[GET],produces=[application/json]}" onto public java.lang.Object org.springframework.boot.actuate.endpoint.mvc.EndpointMvcAdapter.invoke()
2017-12-31 03:19:25.393  INFO 15809 --- [           main] o.s.b.a.e.m.EndpointHandlerMapping       : Mapped "{[/dump || /dump.json],methods=[GET],produces=[application/json]}" onto public java.lang.Object org.springframework.boot.actuate.endpoint.mvc.EndpointMvcAdapter.invoke()
2017-12-31 03:19:25.393  INFO 15809 --- [           main] o.s.b.a.e.m.EndpointHandlerMapping       : Mapped "{[/heapdump || /heapdump.json],methods=[GET],produces=[application/octet-stream]}" onto public void org.springframework.boot.actuate.endpoint.mvc.HeapdumpMvcEndpoint.invoke(boolean,javax.servlet.http.HttpServletRequest,javax.servlet.http.HttpServletResponse) throws java.io.IOException,javax.servlet.ServletException
2017-12-31 03:19:25.394  INFO 15809 --- [           main] o.s.b.a.e.m.EndpointHandlerMapping       : Mapped "{[/info || /info.json],methods=[GET],produces=[application/json]}" onto public java.lang.Object org.springframework.boot.actuate.endpoint.mvc.EndpointMvcAdapter.invoke()
2017-12-31 03:19:25.395  INFO 15809 --- [           main] o.s.b.a.e.m.EndpointHandlerMapping       : Mapped "{[/health || /health.json],produces=[application/json]}" onto public java.lang.Object org.springframework.boot.actuate.endpoint.mvc.HealthMvcEndpoint.invoke(java.security.Principal)
2017-12-31 03:19:25.397  INFO 15809 --- [           main] o.s.b.a.e.m.EndpointHandlerMapping       : Mapped "{[/autoconfig || /autoconfig.json],methods=[GET],produces=[application/json]}" onto public java.lang.Object org.springframework.boot.actuate.endpoint.mvc.EndpointMvcAdapter.invoke()
2017-12-31 03:19:25.398  INFO 15809 --- [           main] o.s.b.a.e.m.EndpointHandlerMapping       : Mapped "{[/env/{name:.*}],methods=[GET],produces=[application/json]}" onto public java.lang.Object org.springframework.boot.actuate.endpoint.mvc.EnvironmentMvcEndpoint.value(java.lang.String)
2017-12-31 03:19:25.398  INFO 15809 --- [           main] o.s.b.a.e.m.EndpointHandlerMapping       : Mapped "{[/env || /env.json],methods=[GET],produces=[application/json]}" onto public java.lang.Object org.springframework.boot.actuate.endpoint.mvc.EndpointMvcAdapter.invoke()
2017-12-31 03:19:25.398  INFO 15809 --- [           main] o.s.b.a.e.m.EndpointHandlerMapping       : Mapped "{[/beans || /beans.json],methods=[GET],produces=[application/json]}" onto public java.lang.Object org.springframework.boot.actuate.endpoint.mvc.EndpointMvcAdapter.invoke()
2017-12-31 03:19:25.553  INFO 15809 --- [           main] c.i.s.s.StudentServicesApplicationTests  : Started StudentServicesApplicationTests in 2.245 seconds (JVM running for 3.231)
Tests run: 1, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 2.334 sec - in com.in28minutes.springboot.studentservices.StudentServicesApplicationTests
Running com.in28minutes.springboot.controller.StudentControllerTest
2017-12-31 03:19:25.574  INFO 15809 --- [           main] .b.t.a.w.s.WebMvcTestContextBootstrapper : Neither @ContextConfiguration nor @ContextHierarchy found for test class [com.in28minutes.springboot.controller.StudentControllerTest], using SpringBootContextLoader
2017-12-31 03:19:25.574  INFO 15809 --- [           main] o.s.t.c.s.AbstractContextLoader          : Could not detect default resource locations for test class [com.in28minutes.springboot.controller.StudentControllerTest]: no resource found for suffixes {-context.xml, Context.groovy}.
2017-12-31 03:19:25.575  INFO 15809 --- [           main] t.c.s.AnnotationConfigContextLoaderUtils : Could not detect default configuration classes for test class [com.in28minutes.springboot.controller.StudentControllerTest]: StudentControllerTest does not declare any static, non-private, non-final, nested classes annotated with @Configuration.
2017-12-31 03:19:25.580  INFO 15809 --- [           main] .b.t.c.SpringBootTestContextBootstrapper : Found @SpringBootConfiguration com.in28minutes.springboot.StudentServicesApplication for test class com.in28minutes.springboot.controller.StudentControllerTest
2017-12-31 03:19:25.585  INFO 15809 --- [           main] .b.t.a.w.s.WebMvcTestContextBootstrapper : Loaded default TestExecutionListener class names from location [META-INF/spring.factories]: [org.springframework.boot.test.mock.mockito.MockitoTestExecutionListener, org.springframework.boot.test.mock.mockito.ResetMocksTestExecutionListener, org.springframework.boot.test.autoconfigure.restdocs.RestDocsTestExecutionListener, org.springframework.boot.test.autoconfigure.web.client.MockRestServiceServerResetTestExecutionListener, org.springframework.boot.test.autoconfigure.web.servlet.MockMvcPrintOnlyOnFailureTestExecutionListener, org.springframework.boot.test.autoconfigure.web.servlet.WebDriverTestExecutionListener, org.springframework.test.context.web.ServletTestExecutionListener, org.springframework.test.context.support.DirtiesContextBeforeModesTestExecutionListener, org.springframework.test.context.support.DependencyInjectionTestExecutionListener, org.springframework.test.context.support.DirtiesContextTestExecutionListener, org.springframework.test.context.transaction.TransactionalTestExecutionListener, org.springframework.test.context.jdbc.SqlScriptsTestExecutionListener]
2017-12-31 03:19:25.588  INFO 15809 --- [           main] .b.t.a.w.s.WebMvcTestContextBootstrapper : Could not instantiate TestExecutionListener [org.springframework.test.context.jdbc.SqlScriptsTestExecutionListener]. Specify custom listener classes or make the default listener classes (and their required dependencies) available. Offending class: [org/springframework/transaction/interceptor/TransactionAttribute]
2017-12-31 03:19:25.589  INFO 15809 --- [           main] .b.t.a.w.s.WebMvcTestContextBootstrapper : Could not instantiate TestExecutionListener [org.springframework.test.context.transaction.TransactionalTestExecutionListener]. Specify custom listener classes or make the default listener classes (and their required dependencies) available. Offending class: [org/springframework/transaction/interceptor/TransactionAttributeSource]
2017-12-31 03:19:25.589  INFO 15809 --- [           main] .b.t.a.w.s.WebMvcTestContextBootstrapper : Using TestExecutionListeners: [org.springframework.test.context.web.ServletTestExecutionListener@78a0ff63, org.springframework.test.context.support.DirtiesContextBeforeModesTestExecutionListener@7c601d50, org.springframework.boot.test.autoconfigure.SpringBootDependencyInjectionTestExecutionListener@79b2852b, org.springframework.test.context.support.DirtiesContextTestExecutionListener@326d27ac, org.springframework.boot.test.mock.mockito.ResetMocksTestExecutionListener@4d499d65, org.springframework.boot.test.autoconfigure.web.servlet.MockMvcPrintOnlyOnFailureTestExecutionListener@313f8301, org.springframework.boot.test.autoconfigure.restdocs.RestDocsTestExecutionListener@5cc9d3d0, org.springframework.boot.test.mock.mockito.MockitoTestExecutionListener@7c2dfa2, org.springframework.boot.test.autoconfigure.web.client.MockRestServiceServerResetTestExecutionListener@661d88a, org.springframework.boot.test.autoconfigure.web.servlet.WebDriverTestExecutionListener@4b0b64cc]

  .   ____          _            __ _ _
 /\\ / ___'_ __ _ _(_)_ __  __ _ \ \ \ \
( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \
 \\/  ___)| |_)| | | | | || (_| |  ) ) ) )
  '  |____| .__|_| |_|_| |_\__, | / / / /
 =========|_|==============|___/=/_/_/_/
 :: Spring Boot ::        (v1.4.4.RELEASE)

2017-12-31 03:19:25.627  INFO 15809 --- [           main] c.i.s.c.StudentControllerTest            : Starting StudentControllerTest on Tadeles-MacBook-Pro.local with PID 15809 (started by tadtab in /Users/tadtab/Documents/student-services)
2017-12-31 03:19:25.627  INFO 15809 --- [           main] c.i.s.c.StudentControllerTest            : No active profile set, falling back to default profiles: default
2017-12-31 03:19:25.987  INFO 15809 --- [           main] o.s.b.t.m.w.SpringBootMockServletContext : Initializing Spring FrameworkServlet ''
2017-12-31 03:19:25.988  INFO 15809 --- [           main] o.s.t.w.s.TestDispatcherServlet          : FrameworkServlet '': initialization started
2017-12-31 03:19:25.995  INFO 15809 --- [           main] o.s.t.w.s.TestDispatcherServlet          : FrameworkServlet '': initialization completed in 7 ms
2017-12-31 03:19:26.022  INFO 15809 --- [           main] c.i.s.c.StudentControllerTest            : Started StudentControllerTest in 0.427 seconds (JVM running for 3.7)
Tests run: 1, Failures: 1, Errors: 0, Skipped: 0, Time elapsed: 0.447 sec <<< FAILURE! - in com.in28minutes.springboot.controller.StudentControllerTest
testSomething(com.in28minutes.springboot.controller.StudentControllerTest)  Time elapsed: 0.012 sec  <<< FAILURE!
java.lang.AssertionError: null
    at org.junit.Assert.fail(Assert.java:86)
    at org.junit.Assert.assertTrue(Assert.java:41)
    at org.junit.Assert.assertNotNull(Assert.java:712)
    at org.junit.Assert.assertNotNull(Assert.java:722)
    at com.in28minutes.springboot.controller.StudentControllerTest.testSomething(StudentControllerTest.java:52)


Results :

Failed tests: 
  StudentControllerTest.testSomething:52 null

Tests run: 2, Failures: 1, Errors: 0, Skipped: 0

[INFO] ------------------------------------------------------------------------
[INFO] BUILD FAILURE
[INFO] ------------------------------------------------------------------------
[INFO] Total time: 5.587 s
[INFO] Finished at: 2017-12-31T03:19:26-05:00
[INFO] Final Memory: 25M/320M
[INFO] ------------------------------------------------------------------------
[ERROR] Failed to execute goal org.apache.maven.plugins:maven-surefire-plugin:2.18.1:test (default-test) on project student-services: There are test failures.
[ERROR] 
[ERROR] Please refer to /Users/tadtab/Documents/student-services/target/surefire-reports for the individual test results.
[ERROR] -> [Help 1]
[ERROR] 
[ERROR] To see the full stack trace of the errors, re-run Maven with the -e switch.
[ERROR] Re-run Maven using the -X switch to enable full debug logging.
[ERROR] 
[ERROR] For more information about the errors and possible solutions, please read the following articles:
[ERROR] [Help 1] http://cwiki.apache.org/confluence/display/MAVEN/MojoFailureException

0 个答案:

没有答案