我有一个使用
formfactory.form().bindFromRequest()
的控制器
当我模拟它时,它会抛出一个 空指针异常 for
bindFromRequest()
即。
when(formfactoryMock.form()).thenReturn(df.bind(params).bindFromRequest());
如何解决?
以下是我如何模拟它来解决类似问题的方法:
import play.data.Form;
import play.data.FormFactory;
import com.fasterxml.jackson.databind.JsonNode;
FormFactory mockFormFactory = mock(FormFactory.class);
Form mockForm = mock(Form.class);
Form mockDataForm = mock(Form.class);
when(mockFormFactory.form(any(Class.class)))
.thenReturn(mockDataForm);
when(mockDataForm.bind(any(JsonNode.class)))
.thenReturn(mockForm);
when(mockForm.hasErrors())
.thenReturn(false); // I was calling hasErrors, You may not be...
when(mockForm.get())
.thenReturn(updatedRecord); // updatedRecord was the model that I needed to pull from the form.
这并不是像OP询问的那样模拟bindFromRequest()方法(它是模拟bind()方法),但概念应该是相同的,只需替换when(mockDataForm.bind(any(JsonNode.class)) ),类似于when(mockDataForm.bindFromResult())
(或者我是这么认为)。
无论如何,我无法找到任何如何在任何地方执行此操作的示例......所以希望这对其他人有帮助。
按照@g_piper的回答,在Play Framework 2.8中我用这种方式解决了这个问题:
@Mock
private FormFactory mockFormFactory;
@Mock
private DynamicForm mockForm;
@Mock
private DynamicForm mockDataForm;
@Before
public void setUp() {
MockitoAnnotations.openMocks(this);
}
@Test
public void test() {
when(mockFormFactory.form()).thenReturn(mockDataForm);
when(mockDataForm.bindFromRequest(any())).thenReturn(mockForm);
when(mockForm.hasErrors()).thenReturn(false); // I was calling hasErrors, You may not be...
when(mockForm.get(anyString())).thenReturn("username"); // updatedRecord was the model that I needed to pull from the form.
//continue with the test code
}