【问题标题】:How to test api using Mockito? Do we need to mock all the class variables?如何使用 Mockito 测试 api?我们需要模拟所有的类变量吗?
【发布时间】: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


【解决方案1】:

你没有说你的 NPE 在哪里......

我想它就在这里:

((OSSDatabase) OSSConfigurationTool.getContext()

当你得到上下文没有?

如果是,您必须模拟 OSSConfigurationTool.getContext() 以返回上下文;)

如果 OSSConfigurationTool 是您必须使用的静态调用(在 junit > 4 中)

@RunWith(PowerMockRunner.class)
@PrepareForTest( OSSConfigurationTool.class )   
public class LoginControllerTest {
...

如果需要,也添加此行

PowerMockito.mockStatic(OSSConfigurationTool.class);

尝试所有这些,让我知道它是否有效

谢谢

【讨论】:

  • 对。我需要模拟调用 OSSConfigurationTool.getContext() 然后在其上调用存根方法。谢谢,它帮助了我。
猜你喜欢
  • 2018-07-03
  • 1970-01-01
  • 1970-01-01
  • 2012-02-18
  • 2018-12-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多