【发布时间】:2017-12-17 08:37:16
【问题描述】:
我有一个简单的 Spring boot Rest 应用程序,它从数据库返回用户列表。 应用程序按预期工作,但测试场景失败并出现错误。经过长时间的谷歌搜索无法弄清楚为什么? 似乎测试类无法访问 userRepository,而不是调用 userRepository.getAllUsers,而是调用 AppController.getAllUsers。
org.springframework.web.util.NestedServletException: Request processing failed; nested exception is java.lang.NullPointerException
……………………………
Caused by: java.lang.NullPointerException
at com.loan.demo.controller.AppController.getAllUsers(AppController.java:43)
…………………………………………..
这些是我的课程: LoanAppApplication
@SpringBootApplication
public class LoanAppApplication {
public static void main(String[] args) {
SpringApplication.run(LoanAppApplication.class, args);
}
}
类 User.java
@Entity
@Table(name="USERTABLE")
public class User {
private int id;
@NotNull
private String firstName;
@NotNull
private String lastName;
@NotNull
private String persID;
private int blocked;
private Set<Loan> loans;
public User() {
}
public User(String firstName, String lastName, String persID) {
this.firstName = firstName;
this.lastName = lastName;
this.persID = persID;
}
用户存储库:
@Repository
public interface UserRepository extends JpaRepository<User, Integer>{
public User findById(int Id);
public User findByPersID(String userId);
}
和休息控制器:
@RestController
public class AppController {
@Autowired
UserRepository userRepository;
@GetMapping("/doit")
public String doIt() {
return "Do It";
}
//list all users
@GetMapping("/users")
public List<User> getAllUsers() {
return userRepository.findAll(); // this is line 43 from debuging error log
}
}
和测试类:
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = {LoanAppApplication.class})
public class LoanAppApplicationTests {
private MockMvc mockMvc;
@InjectMocks
private AppController appController;
@Before
public void addData() {
mockMvc = MockMvcBuilders.standaloneSetup(appController)
.build();
}
//First test scenario that return only string works perfectly
@Test
public void testData() throws Exception {
mockMvc.perform(get("/doit")
)
.andExpect(status().isOk())
.andExpect(content().string("Do It"));
}
//but second that should return empty json string fails with exception
@Test
public void testGet() throws Exception {
mockMvc.perform(get("/users")
)
.andExpect(status().isOk())
.andExpect(content().string("Do It")); //this test should fail but not return exception
}
}
【问题讨论】:
标签: java unit-testing spring-boot-test