如何在枚举类中测试方法?为什么我的测试代码没有触发提到的方法?

发布于 2025-02-01 00:37:52 字数 951 浏览 4 评论 0原文

我正在尝试嘲笑该类并使用该类调用方法,但是由于某种原因,该方法没有被启动。

课程

public enum Square {    
    
    SQUARE_SET(3);
    private final int a;

    Square(int l) {
        this.a = l*l;
    }
     
    public int getSquare() {
        return a;
    }//can not trigger this method

    @Override
    public String toString() {
        StringBuilder sb = new StringBuilder("Area :");
        sb.append(a);
        return sb.toString();
    }//can not trigger this method
}

要测试我的代码以测试上述课程的

class SquareTest {

    int l;
    private int a;

    @Test
    void testGetSquare() {
        Square Square = mock(Square.class);
        assertEquals(a, Square.getSquare());
    }

    void testToString() {
        Square Square = mock(Square.class);
        StringBuilder sb = new StringBuilder("Area :");
        sb.append(a);
        sb.toString();
        when(Square.toString()).thenReturn(sb.toString());
    }
}

I'm trying to mock the class and call the methods using that, but for some reason the methods are not being initiated.

The class to be tested

public enum Square {    
    
    SQUARE_SET(3);
    private final int a;

    Square(int l) {
        this.a = l*l;
    }
     
    public int getSquare() {
        return a;
    }//can not trigger this method

    @Override
    public String toString() {
        StringBuilder sb = new StringBuilder("Area :");
        sb.append(a);
        return sb.toString();
    }//can not trigger this method
}

My code for testing the above class

class SquareTest {

    int l;
    private int a;

    @Test
    void testGetSquare() {
        Square Square = mock(Square.class);
        assertEquals(a, Square.getSquare());
    }

    void testToString() {
        Square Square = mock(Square.class);
        StringBuilder sb = new StringBuilder("Area :");
        sb.append(a);
        sb.toString();
        when(Square.toString()).thenReturn(sb.toString());
    }
}

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文