Java study notes-the role of @RunWith(SpringRunner.class)

Suggested reading: https://blog.csdn.net/u011835956/article/details/113950577

Note: Tests are all based on the case written by Junit, not based on the TestNg framework. If it is the TestNg framework, it should inherit AbstractTestNGSpringContextTests, so that the bean has the ability to inject

 

Write the test locally, run it and always report a null pointer error, and then start Springboot locally, it shows that the bean is injected, but as long as it is executed, it reports a null pointer. This is the code before modification as follows

public class TestApplicationTests {
    @Autowired
    UserService userService;

    @Test
    public void contextLoads() {
        User s=userService.getName("ssss");
        System.out.println("该用户ID为:"+s.getName());

    }

}

The results after running are as follows:

 

Later, I read other people's code and found it! ! ! !

The role of @RunWith(SpringRunner.class) indicates that the Test test class should use injected classes, such as @Autowired injected classes. With @RunWith(SpringRunner.class) these classes can be instantiated into the spring container, and automatic injection can take effect.

 

The modified code is as follows:

@RunWith(SpringRunner.class)
@SpringBootTest
public class TestApplicationTests {
    @Autowired
    UserService userService;

    @Test
    public void contextLoads() {
        User s=userService.getName("ssss");
        System.out.println("该用户ID为:"+s.getName());

    }

}

It runs successfully.

 

 

Guess you like

Origin blog.csdn.net/mumuwang1234/article/details/115129688