gpt4 book ai didi

java - 如何用 Java 为该服务编写 TestCase?

转载 作者:行者123 更新时间:2023-11-30 11:12:10 25 4
gpt4 key购买 nike

我有一门课

public class AuthenticationModule {

String userName = "foo";
String password = "bar";

public void setUserName(String userName) {
this.userName = userName;
}

public void setPassword(String password ) {
this.password = password ;
}

AuthenticationServicePort authenticationServicePort;
AuthenticationService port;

private boolean authenicate(String userName, String password) {

authenticationServicePort = new AuthenticationServicePort();
port = authenticationServicePort.getAuthenticationServiceProxy();
return port.login(userName, password);
}

public boolean validateUser() {

return authenicate(userName, password);
}
}

AuthenticationServicePort 返回一个 WSDL 端口我想创建一个带有 Mock AuthenticationServicePort 的简单测试用例,它将返回一个“true/false”值

如何在不更改 java 代码的情况下注入(inject)我自己的 MockObject?或者更糟糕的情况,更改为更容易测试的最简单方法是什么。

最佳答案

您应该避免创建内部有任何逻辑的类实例(不是普通的 DTO 对象)。相反,您应该以依赖注入(inject)容器可以构建完整的对象图的方式设计您的类。在您的代码中,您需要自己回答是否每次调用 authenicate 方法都需要一个新的 AuthenticationServicePort 实例?如果是,那么您应该使用 factory模式来创建这个对象的实例,这个工厂应该被注入(inject)(在构造函数中提供),这样你就可以模拟它以及它将产生的一切。如果 authenticate 方法的多次调用可以重用 AuthenticationServicePort 的相同实例,则只需注入(inject)它(在构造函数中提供)并在您的测试中提供模拟而不是实际实现。

关于java - 如何用 Java 为该服务编写 TestCase?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27031954/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com