编写java代码时的gradle构建问题

问题描述 投票:0回答:1

我已经从 github 克隆了 java 上的主管代码,该代码附带了一些 Greeting.test 文件和其他文件,在我在 src/test/java 中编写了 Greeting.java 代码并运行代码后,我不断收到这样的消息:

"message": "The method createGreeting(String) is undefined for the type Greeting"

这是一条与 graddle 构建失败相关的消息,我正在考虑如何解决这个问题,以便当我将代码提交到 github 时可能不会出现错误?

我尝试注释 Greeting.test 中生成错误的行,但它甚至带来了更多错误,我还尝试遵循堆栈溢出的一些不同解决方案,例如在启动 createGreeting 的方法后面添加 Greeting 类,但它仍然可以不行。我希望它能够使构建成功,但事实并非如此。

这些是 Greeting.test 代码

import org.junit.jupiter.api.Test;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.PrintStream;

import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertTrue;

public class GreetingTest {

    @Test
    public void testCreateGreeting() {
        Greeting greeting = new Greeting();
        String name = "Alice";
        assertEquals("Hello, Alice!", greeting.createGreeting(name), "Greeting message should match expected output.");
    } 

    @Test
    public void testMainOutput() {
        ByteArrayInputStream in = new ByteArrayInputStream("Alice\n".getBytes());
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        System.setIn(in);
        System.setOut(new PrintStream(out));

        String[] args = {};
        Greeting.main(args);

        String consoleOutput = out.toString();
        assertTrue(consoleOutput.contains("Hello, Alice!"), "The output should contain the correct greeting.");
    }

}

这些是我创建的 Greeting.java 类的代码:

import java.util.Scanner;

public class Greeting {
    public static void main(String[] args) {

        Scanner userInput = new Scanner(System.in);

        System.out.println("Please enter your first name : ");
        String userName = userInput.next();

        System.out.println("Hello " + userName);

    }
}
java github android-gradle-plugin gradlew
1个回答
0
投票

您可以简单地在

createGreeting
类中的
... main(...)
方法旁边添加所需的方法
Greeting
,例如

public class Greeting {
    // a `static` method which can be called without an instance of `Greeting`
    public static void main(String[] args) {
        // current code
    }
    
    // an instance method which needs an instance to be called => `new Greeting()`
    public String createGreeting(String value) {
        // do whats ever necessary to fullfill the assert in the test
    }
}

如果创建新的

Greeting
类,则可以省略
main
方法。您还可以省略当前
main
类中的
Greeting
方法,因为单元测试不需要它。

© www.soinside.com 2019 - 2024. All rights reserved.