Java 使用Spring引导REST API Crud的JUnit中出现Null错误
下面是我的测试代码,结果是NULLJava 使用Spring引导REST API Crud的JUnit中出现Null错误,java,spring,spring-boot,Java,Spring,Spring Boot,下面是我的测试代码,结果是NULL public class MybatisApplicationTests { @InjectMocks UserController uc; @Mock UserService userService; @Test public void getUserByIdTest() { Long id= 6L; assertNotNull(uc.getUserById(id)); } } 我的控制器UserController.java如下所示
public class MybatisApplicationTests {
@InjectMocks
UserController uc;
@Mock
UserService userService;
@Test
public void getUserByIdTest() {
Long id= 6L;
assertNotNull(uc.getUserById(id));
}
}
我的控制器UserController.java如下所示
@GetMapping("/getUserById/{id}")
public User getUserById(@PathVariable("id") Long id) {
User user = userService.getUserById(id);
return user;
}
@Override
public User getUserById(@PathVariable("id") Long id) {
User user = userMapper.getUserById(id);
return user;
}
我的getUserById的ServiceImpl.java如下所示
@GetMapping("/getUserById/{id}")
public User getUserById(@PathVariable("id") Long id) {
User user = userService.getUserById(id);
return user;
}
@Override
public User getUserById(@PathVariable("id") Long id) {
User user = userMapper.getUserById(id);
return user;
}
当运行上面的代码时,我得到下面的错误
org.opentest4j.AssertionFailedError: expected: not <null>
at org.junit.jupiter.api.AssertionUtils.fail(AssertionUtils.java:39)
at org.junit.jupiter.api.Assertions.fail(Assertions.java:109)
org.opentest4j.AssertionFailedError:应为:非
位于org.junit.jupiter.api.AssertionUtils.fail(AssertionUtils.java:39)
位于org.junit.jupiter.api.Assertions.fail(Assertions.java:109)
请帮助我解决同样的问题&提前感谢。您必须初始化您的模拟,然后声明您的模拟行为,尝试这样更改您的测试类:
public class MybatisApplicationTests {
@InjectMocks
UserController uc;
@Mock
UserService userService;
@Before
void setUp(){
initMocks(this);
}
@Test
public void getUserByIdTest() {
Long id= 6L;
User mockUser = mock(User.class);
when(userService.getUserById(id)).thenReturn(mockUser);
User actual = uc.getUserById(id);
assertEquals(userMock, actual);
}
}
您必须初始化您的模拟,然后必须声明您的模拟行为,尝试这样更改您的测试类:
public class MybatisApplicationTests {
@InjectMocks
UserController uc;
@Mock
UserService userService;
@Before
void setUp(){
initMocks(this);
}
@Test
public void getUserByIdTest() {
Long id= 6L;
User mockUser = mock(User.class);
when(userService.getUserById(id)).thenReturn(mockUser);
User actual = uc.getUserById(id);
assertEquals(userMock, actual);
}
}
我认为这就是你的解决方案所缺少的
我认为这就是你的解决方案所缺少的