在嘗試為以下代碼運行我的測驗時。我在下面詳細介紹了一些錯誤。
當我嘗試運行我的測驗時,我觀察到它mkdirs()在我的代碼中引發呼叫。IllegalArgumentException
MyClass.java
package com.javaeasily.demos.junit;
import java.util.ArrayList;
public class MyClass {
private final NodeHelper nodeHelper;
private static final ArrayList<String> ACTIVE_SERVICES_POST_RECONFIGURE = new ArrayList<>();
// Only allow construction if number is greater than one
MyClass() {
ACTIVE_SERVICES_POST_RECONFIGURE.add("my-node-" NodeUtils.getMyNode());
nodeHelper = new NodeHelper();
}
public void reconfigureNode() {
if (ACTIVE_SERVICES_POST_RECONFIGURE.isEmpty()) {
return;
}
try {
nodeHelper.createStagingDir();
} catch (Exception e) {
throw new RuntimeException("Cannot reconfigure node");
}
}
}
NodeUtils.java
package com.javaeasily.demos.junit;
import org.apache.commons.lang3.StringUtils;
public class NodeUtils {
private static final String HOSTNAME_PREFIX = "my-node-";
public static String hostnameToNode(String hostname) {
if (!hostname.startsWith(HOSTNAME_PREFIX)) {
throw new IllegalArgumentException(hostname " is not recognized hostname");
}
return StringUtils.removeStart(hostname, HOSTNAME_PREFIX);
}
public static String getHostname() {
return System.getenv("HOSTNAME");
}
public static String getMyNode() {
return hostnameToNode(getHostname());
}
}
節點助手.java
package com.javaeasily.demos.junit;
import java.io.File;
public class NodeHelper {
private static final String STAGING_DIR = "/staging/";
public void createStagingDir() {
File stagingDir = new File(STAGING_DIR);
if (!stagingDir.exists() && !stagingDir.mkdirs()) {
throw new IllegalArgumentException("Could not create staging dir");
}
}
}
MyClassTest.java
package com.javaeasily.demos.junit;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.MockedStatic;
import org.mockito.Mockito;
import org.mockito.junit.jupiter.MockitoExtension;
@ExtendWith(MockitoExtension.class)
public class MyClassTest {
private MyClass myclass;
@BeforeEach
public void SetUp() {
try (MockedStatic<NodeUtils> nodeUtilsMockedStatic = Mockito.mockStatic(NodeUtils.class);) {
nodeUtilsMockedStatic.when(NodeUtils::getMyNode).thenReturn("foo");
myclass = new MyClass();
}
}
@Test
public void testReconfigureNode() {
myclass.reconfigureNode();
}
}
當我嘗試運行測驗時,出現以下錯誤:
java.lang.RuntimeException: Cannot reconfigure node
at com.javaeasily.demos.junit.MyClass.reconfigureNode(MyClass.java:22)
除錯后我看到:
java.lang.IllegalArgumentException: Could not create staging dir
有人愿意告訴我我做錯了什么嗎?
uj5u.com熱心網友回復:
要模擬NodeHelper,您不應該在內部創建它MyClass,而是通過建構式從外部注入它。IE
MyClass(Nodehelper nodeHelper) {
ACTIVE_SERVICES_POST_RECONFIGURE.add("my-node-" NodeUtils.getMyNode());
this.nodeHelper = nodeHelper;
}
這允許您NodeHelper在測驗中創建一個模擬,將其傳遞給MyClass并將所需的行為設定為預期。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/494602.html
