我正在开发一个应用程序,我必须为我的代码编写测试。我正在为我的用户服务类编写一个测试。这是我的用户服务类:
private static final Logger LOG = LoggerFactory.getLogger("userLogger");
@EJB
UserDAO userDAO;
@Override
public List<User> list() {
LOG.info("Get all users!");
return Optional.ofNullable(userDAO.findAll())
.orElse(Collections.emptyList()).stream().map(u -> u.toUser())
.collect(Collectors.toList());
}
@Override
public User findById(long id) {
UserEntity userEntity = userDAO.find((id));
if (userEntity == null) {
throw new UserNotFoundException(id);
}
LOG.info("User founded with id {}", id);
return userEntity.toUser();
}
@Override
public User create(User user) {
if (user == null) {
throw new ServiceException("Invalid request!");
}
UserEntity exists = userDAO.find(user.getId());
if (exists != null) {
throw new UserAlreadyExistsException(user.getId());
}
UserEntity userEntity = new UserEntity(user);
userDAO.create(userEntity);
LOG.info("Created user with id {}. Username is {}. Name is {}. Surname is {}. Email is {}.",
userEntity.getUserId(), userEntity.getUsername(), userEntity.getName(),
userEntity.getSurname(), userEntity.getEmail());
return userEntity.toUser();
}
@Override
public User update(long id, User user) {
if (user == null) {
throw new ServiceException("Invalid request!");
}
UserEntity userEntity = userDAO.find((id));
if (userEntity == null) {
throw new UserNotFoundException(id);
}
userEntity.update(user);
userDAO.update(userEntity);
return userEntity.toUser();
}
@Override
public void delete(long id) {
UserEntity userEntity = userDAO.find(id);
if (userEntity == null) {
throw new UserNotFoundException(id);
}
userDAO.delete(userEntity);
LOG.info("Deleted user with id {}", userEntity.getUserId());
}
}
这是我的测试类:
private static User useric;
@Spy
@InjectMocks
UserService userService;
@Mock
UserDAO userDAO;
@BeforeMethod
public void setUp() throws Exception {
MockitoAnnotations.initMocks(this);
UserEntity userEntity = mock(UserEntity.class);
willReturn(mock(User.class)).given(userEntity).toUser();
//willReturn(userEntity).given(userDAO).find(0L);
useric = new User(7, "DDD", "SDSDS", "SAAsd", "qwqwqw@gmail.com");
}
@Test
public void testWhenUserExist() throws Exception {
//User goran = new User(5, "goran1992", "goran", "palibrk", "palibrk.goran@gmail.com");
//User user = userService.create(goran);
// GIVEN
User user = userService.create(useric);
//long userId = 0;
// WHEN
// user = userService.findById(goran.getId());
// THEN
assertNotNull(user);
Assert.assertEquals(7, user.getId());
//verify(userService, Mockito.times(1)).findById(userId);
}
@Test(expectedExceptions = ServiceException.class, expectedExceptionsMessageRegExp = "user-service: User with id: 35 was not found!")
public void testWhenUserNotExist() throws Exception {
// GIVEN
long userId = 35;
// WHEN
userService.findById(userId);
// THEN
fail();
}
@Test
public void testCreateUser() throws Exception{
User user = userService.create(useric);
assertNotNull(user);
Assert.assertEquals(useric.getName(), user.getName());
//User userEntity = new User(1, "aaaewwe", "bbbb", "abba", "asa@gmail.com");
//User user = userService.create(userEntity);
// Assert.assertEquals(user, user);
//assertNotNull(user);
// Assert.assertEquals(userEntity, user);
// verify(userService, Mockito.times(1)).create(userEntity);
}
@Test
public void testDeleteUser() throws Exception{
User user = userService.create(useric);
userService.findById(user.getId());
userService.delete(user.getId());
//verify(userService, Mockito.times(1)).delete(useric.getId());
}
当我运行此测试时,出现此错误:
[TestNG] Running:
C:UserspgoranAppDataLocalTemptestng-eclipse--1992695267testng-customsuite.xml
[main] INFO userLogger - Created user with id 7. Username is DDD. Name is SAAsd. Surname is SDSDS. Email is qwqwqw@gmail.com.
[main] INFO userLogger - Created user with id 7. Username is DDD. Name is SAAsd. Surname is SDSDS. Email is qwqwqw@gmail.com.
[main] INFO userLogger - Created user with id 7. Username is DDD. Name is SAAsd. Surname is SDSDS. Email is qwqwqw@gmail.com.
PASSED: testCreateUser
PASSED: testWhenUserExist
PASSED: testWhenUserNotExist
FAILED: testDeleteUser
com.comtrade.trips.service.user.exception.UserNotFoundException: user-service: User with id: 7 was not found!
at com.comtrade.trips.service.user.UserService.findById(UserService.java:45)
at com.comtrade.trips.service.user.UserServiceImplementationTest.testDeleteUser(UserServiceImplementationTest.java:99)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at org.testng.internal.MethodInvocationHelper.invokeMethod(MethodInvocationHelper.java:104)
at org.testng.internal.Invoker.invokeMethod(Invoker.java:645)
at org.testng.internal.Invoker.invokeTestMethod(Invoker.java:851)
at org.testng.internal.Invoker.invokeTestMethods(Invoker.java:1177)
at org.testng.internal.TestMethodWorker.invokeTestMethods(TestMethodWorker.java:129)
at org.testng.internal.TestMethodWorker.run(TestMethodWorker.java:112)
at org.testng.TestRunner.privateRun(TestRunner.java:756)
at org.testng.TestRunner.run(TestRunner.java:610)
at org.testng.SuiteRunner.runTest(SuiteRunner.java:387)
at org.testng.SuiteRunner.runSequentially(SuiteRunner.java:382)
at org.testng.SuiteRunner.privateRun(SuiteRunner.java:340)
at org.testng.SuiteRunner.run(SuiteRunner.java:289)
at org.testng.SuiteRunnerWorker.runSuite(SuiteRunnerWorker.java:52)
at org.testng.SuiteRunnerWorker.run(SuiteRunnerWorker.java:86)
at org.testng.TestNG.runSuitesSequentially(TestNG.java:1293)
at org.testng.TestNG.runSuitesLocally(TestNG.java:1218)
at org.testng.TestNG.runSuites(TestNG.java:1133)
at org.testng.TestNG.run(TestNG.java:1104)
at org.testng.remote.AbstractRemoteTestNG.run(AbstractRemoteTestNG.java:132)
at org.testng.remote.RemoteTestNG.initAndRun(RemoteTestNG.java:236)
at org.testng.remote.RemoteTestNG.main(RemoteTestNG.java:81)
===============================================
Default test
Tests run: 4, Failures: 1, Skips: 0
===============================================
===============================================
Default suite
Total tests run: 4, Failures: 1, Skips: 0
===============================================
[TestNG] Time taken by org.testng.reporters.JUnitReportReporter@7fc229ab: 18 ms
[TestNG] Time taken by [FailedReporter passed=0 failed=0 skipped=0]: 17 ms
[TestNG] Time taken by org.testng.reporters.jq.Main@27ae2fd0: 68 ms
[TestNG] Time taken by org.testng.reporters.XMLReporter@15b204a1: 11 ms
[TestNG] Time taken by org.testng.reporters.EmailableReporter2@56a6d5a6: 9 ms
[TestNG] Time taken by org.testng.reporters.SuiteHTMLReporter@45b9a632: 33 ms
我看到我的错误是找不到 id=7 的用户,但我不知道当我在删除方法中使用该 id 创建具有该 id 的用户时。 问题是,如何解决此错误?
public void delete(long id) { UserEntity userEntity = userDAO.find(id);
你的userDAO
是一个模拟,它没有配置为返回ID 7的东西,因此它返回一个null
加
willReturn(userEntity).given(userDAO).find(7L);
到测试的//Given
部分