我是mockito / Java Spring的新手,我尝试进行测试。我有一个管理控制器,其中包含以下方法:
@RequestMapping(value="/admin/users", method = RequestMethod.GET)
public ResponseEntity<List<User>>users(){
List<User> students=this.userService.getAll();
if(students.isEmpty())
return new ResponseEntity<List<User>>(HttpStatus.NO_CONTENT);
return new ResponseEntity<List<User>>(students,HttpStatus.OK);
}
现在,我尝试进行测试,看看它是否有效,如下所示:
public class AdminControllerTest {
@InjectMocks
private AdminController controller;
@InjectMocks
private UserServiceImpl userService = new UserServiceImpl();
@Mock
private UserRepository userRepository;
private MockMvc mockMvc;
@Before
public void setup(){
MockitoAnnotations.initMocks(this);
mockMvc = MockMvcBuilders.standaloneSetup(controller).build();
}
@Test
public void test() throws Exception {
User user = new User();
user.setId(5);
user.setActive(true);
user.setLastName("Test1");
user.setName("Test1");
user.setPassword("123123");
user.setRole(User.Role.student);
user.setEmail("[email protected] /cdn-cgi/l/email-protection");
when(userService.save(user)).thenReturn(user);
userService.save(user);
mockMvc.perform(get("/admin/users")).andDo(print());
}
}
问题是我不确定如何使 Test 类将项目添加到存储库中。我尝试了这种方法,但出现 NullPointerExceptions。我猜测这是因为存储库是空的,并且当调用 .getAll() 方法时它会返回错误。
由于您已经模拟了存储库,因此不需要将内容保存到其中。您需要做的就是指定调用某些方法时存储库将返回的内容。
代替:
when(userService.save(user)).thenReturn(user);
...尝试使用:
when(userRepository.findAll()).thenReturn(Collections.singletonList(user));
为什么它不起作用
您收到 NullPointerException 的原因之一是:
- 你正在设置一个
when
在一个甚至不是模拟的对象上,和/或
-
你没有提供when
为了userRepository.findAll()
方法,所以当你调用它时它返回 null:
List<User> students=this.userService.getAll(); <-- returned null
...然后被取消引用并抛出 NPE:
if(students.isEmpty()) <-- throws NPE when students is null
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)