相关疑难解决方法(0)

弹簧测试和maven

我正在尝试测试我的Spring网络应用程序,但我遇到了一些问题.

我在我的maven中添加了一个测试类

@RunWith( SpringJUnit4ClassRunner.class )
@ContextConfiguration
public class UserServiceTest {

    @Autowired
    private UserService userService;

    @Test
    public void testName() throws Exception {
        List<UserEntity> userEntities = userService.getAllUsers();

        Assert.assertNotNull(userEntities);
    }
}
Run Code Online (Sandbox Code Playgroud)

但是NullPointerException当我尝试运行此测试时,我得到了一个用户服务.IntelliJ说"无法自动装配.没有找到'UserService'类型的bean.添加后@RunWith(SpringJUnit4ClassRunner.class),我得到了这个例外

java.lang.IllegalStateException: Neither GenericXmlContextLoader nor AnnotationConfigContextLoader was able to detect defaults, and no ApplicationContextInitializers were declared for context configuration
Run Code Online (Sandbox Code Playgroud)

我怎么解决呢?我想我需要在我的tomcat服务器上运行这个测试但是我如何使用IntelliJ进行测试?(比如命令'mvn clean install tomcat7:run-war-only')

java junit spring intellij-idea maven

3
推荐指数
1
解决办法
4054
查看次数

Spring Boot控制器单元测试:无法加载ApplicationContext

我有一个简单的spring boot控制器,我想为其编写单元测试,但是有错误。我已经搜索了几个小时,但仍然找不到解决方案。这是代码:

HelloController.java

@RestController
public class HelloController {

    @Autowired
    private HelloService helloService;

    @GetMapping("/hello")
    public String sayHello(){
        return helloService.sayHello();
    }
}
Run Code Online (Sandbox Code Playgroud)

HelloService.java:

@Service
public class HelloService {
    public String sayHello(){
        return "Hello";
    }
}
Run Code Online (Sandbox Code Playgroud)

和单元测试文件:HelloControllerTest.java:

@RunWith(SpringJUnit4ClassRunner.class)
@WebMvcTest(HelloController.class)
public class HelloControllerTest {

    @Autowired
    private MockMvc mockMvc;

    @Mock
    private HelloService helloService;


    @Before
    public void setUp(){
        MockitoAnnotations.initMocks(this);
    }

    @Test
    public void sayHello() throws Exception {
        when(helloService.sayHello()).thenReturn("thach");
        mockMvc.perform(get("/hello"))
                .andExpect(status().isOk())
                .andExpect(content().string("thach"));
    }

}
Run Code Online (Sandbox Code Playgroud)

但是有一个错误:

java.lang.IllegalStateException: Failed to load ApplicationContext

    at org.springframework.test.context.CacheAwareContextLoaderDelegate.loadContext(CacheAwareContextLoaderDelegate.java:99)
    at org.springframework.test.context.TestContext.getApplicationContext(TestContext.java:122)
    at org.springframework.test.context.web.ServletTestExecutionListener.setUpRequestContextIfNecessary(ServletTestExecutionListener.java:105)
    at …
Run Code Online (Sandbox Code Playgroud)

unit-testing spring-boot

0
推荐指数
2
解决办法
6241
查看次数

标签 统计

intellij-idea ×1

java ×1

junit ×1

maven ×1

spring ×1

spring-boot ×1

unit-testing ×1