当junit中的方法返回null时,mockito
我一直在使用mockito编写测试用例。下面是我在测试用例中的代码当junit中的方法返回null时,mockito,junit,mockito,Junit,Mockito,我一直在使用mockito编写测试用例。下面是我在测试用例中的代码 @RunWith(SpringRunner.class) public class LoginControllerTest { private MockMvc mockMvc; @InjectMocks private LoginService loginService; @Mock private LoginController loginController;
@RunWith(SpringRunner.class)
public class LoginControllerTest {
private MockMvc mockMvc;
@InjectMocks
private LoginService loginService;
@Mock
private LoginController loginController;
@Before
public void setup() {
MockitoAnnotations.initMocks(this);
// Setup Spring test in standalone mode
mockMvc = MockMvcBuilders.standaloneSetup(loginController).build();
}
@Test
public final void test() throws Exception {
// Assign
when(loginService.test()).thenReturn("hello");
// act
mockMvc.perform(get("/hello"))
// Assertion
.andExpect(status().isOk())
.andExpect(content().string("Message from service: hello"));
verify(loginService).test();
}
@Test
public final void usernameInvalidAndPassword() throws Exception {
User userData = new User();
userData.setUserName("akhila.s@cloudium.io");
userData.setPassword("Passw0rd");
User userDataNew = new User();
userDataNew.setUserName("akhila.s@cloudium.io");
userDataNew.setPassword("Passw0rd");
JSONObject requestBody = new JSONObject();
requestBody.put("userName", "akhila.s@cloudium.io");
requestBody.put("password", "Passw0rd");
JSONObject responseBody = new JSONObject();
responseBody.put("status_code", "200");
responseBody.put("message", "ok");
// Assign
when(loginService.saveUser(userData)).thenReturn(userDataNew);
// act
mockMvc.perform(get("/login")
.param("userName", "akhila.s@cloudium.io")
.param("password", "Passw0rd"))
// Assertion
.andExpect(status().isOk()).andExpect(content().json(responseBody.toString())).andDo(print());
}
对于第一个测试用例,它工作正常,但是对于第二个测试,它总是返回null。有人能帮忙吗?提前感谢您的LoginController和LoginService上的注释错误。您正在测试控制器,因此不想对其进行模拟,您正在对服务上的方法进行存根,因此这需要进行模拟:
@Mock
private LoginService loginService;
@InjectMocks
private LoginController loginController;
我认为你必须: 1)基于
username
和password
引入equals方法,因为在测试方法中创建的用户对象与您在测试中创建和使用的实例不同
2)在设置中使用通配符:
when(loginService.saveUser(Mockito.any(User.class))).thenReturn(userDataNew);