【发布时间】:2014-11-10 11:44:06
【问题描述】:
我想测试一个使用这么多类变量的 API,而且在方法中还有这么多其他方法调用,我不知道如何全部模拟它们,或者我需要一种不同的方法。
请帮我解决这个问题,我提供以下代码:
public class LoginController implements Initializable
{
protected static BorderPane choose;
protected static VBox menu;
@FXML
private BorderPane loginPane;
@FXML
private Label errorText;
@FXML
private PasswordField password;
@FXML
private Label databaseName;
@FXML
private Label host;
@FXML
private Button login;
@FXML
private TextField userId;
BaseFrame mainController = BaseFrame.getMainController();
@Override
public void initialize(URL arg0, ResourceBundle arg1)
{
assert login != null : "fx:id=\"login\" was not injected: check your FXML file 'Login.fxml'.";
OSSDatabase ossDatabase = (OSSDatabase) OSSConfigurationTool.getContext().getBean("ossDatabase");
this.databaseName.setText(ossDatabase.getName());
this.host.setText(ossDatabase.getHost());
login.setOnAction(new EventHandler<ActionEvent>()
{
@Override
public void handle(ActionEvent event)
{
String username = userId.getText().trim();
String credentials = password.getText().trim();
if (isValid(username) && isValid(credentials))
{
errorText.setText("");
UserManager userManager = (UserManager) OSSConfigurationTool.getContext().getBean("UserManager");
try
{
userManager.login(username, credentials, true);
FXMLLoader menuLoader = new FXMLLoader(LoginController.class.getResource("/com/capsilon/oss/configuration/tool/view/mainMenu.fxml"));
try
{
mainController.getMenuPane().setVisible(true);
mainController.getMenuPane().add((VBox) menuLoader.load(), 0, 1);
} catch (IOException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
} catch (OSSException e)
{
e.printStackTrace();
errorText.setText(e.getErrorCode().name());
errorText.setTooltip(new Tooltip(e.getMessage()));
}
}
else
{
errorText.setText("Username or Password is empty");
}
}
});
}
}
在为此方法创建测试时,我编写了以下测试方法,该方法最初给出 NPE 并且没有进一步进行。
public class LoginControllerTest
{
@Mock
OSSDatabase ossDatabase;
@Mock
private TextField userId;
@Mock
private PasswordField password;
LoginController controller = new LoginController();
@Before
public void setUp() throws Exception
{
}
@Test
public final void testInitialize()
{
URL url = PowerMockito.mock(URL.class);
ResourceBundle bundle = Mockito.mock(ResourceBundle.class);
Mockito.when((OSSDatabase) OSSConfigurationTool.getContext().getBean("ossDatabase")).thenReturn(ossDatabase);
Mockito.when(ossDatabase.getName()).thenReturn("SomeName");
Mockito.when(ossDatabase.getHost()).thenReturn("SomeHost");
Mockito.when(userId.getText().trim()).thenReturn("userName");
controller.initialize(url, bundle);
}
}
虽然我已经对一些方法调用进行了存根,但仍然对这是否是正确的方法感到困惑。请帮我。提前致谢。
【问题讨论】:
-
将您的困难视为代码异味,即班级做得太多。将业务/数据库过程与视图操作过程分开可能会使每一部分都更容易测试。
-
同意。你肯定想要分离关注点,这是面向对象编程的目标之一。
标签: java unit-testing testing mockito