【发布时间】:2019-03-21 23:35:31
【问题描述】:
这是我的第一个类,其中构造函数有一个对象调用其他类中的方法。
Class Search{
public Search(String username, JSONObject accounts) throws Exception {
Credentials credentials = new Credentials(username);
String Uid = credentials.getUserName();
String Pwd = new String(credentials.getCredentials().getPassword());
}
public getDOB(){
--------------------
-------------
}
}
班级证书:
import javax.resource.spi.security.PasswordCredential;
Public class Credentials{
public Credentials(String name){
}
public PasswordCredential getCredentials(){
return passwordCredential;
}
public String getUserName(){
PasswordCredential localCredential = getCredentials();
return localCredential.getUsername();
}
}
类测试:
@RunWith(PowerMockRunner.class)
@PrepareForTest({Search.class, Credentials.class})
public class JunitTest {
@Test
public void playTest() {
PasswordCredential pwdCreds = new PasswordCredential();
pwdCreds.setPassword("test");
Credentials credentials = new Credentials("user");
Credentials credentials = Mockito.spy(credentials);
Mockito.doReturn(pwdCreds).when(credentials).getCredentials();
Mockito.doReturn("cmApptest").when(credentials).getUserName();
Search search = new Search("username", jsonobject);
search.getDOB();
}
}
每当我调试测试类时,它都会执行getCredentials 和getUserName 方法,即使在我模拟它们之后也是如此。我期待实际的方法不会执行,而是应该返回我在 JunitTest 类中提到的值。
【问题讨论】:
-
此代码无法编译。您定义了 credentials 两次。您永远不会使用 person1。 pwdCreds 在哪里定义?我没有做过很多模拟,但你为什么使用跑步者 PowerMockRunner.class 却使用 Mockito?也许没关系,但作为一个嘲弄的新手,这对我来说似乎不匹配。
-
刚才我已经编辑过,现在您看到的是正确的副本。
-
@蝙蝠侠:不是这样;你仍然声明
credentials两次,这是一个编译错误。
标签: java mockito junit4 powermockito