猿问

JMockit - 意外调用

我有一个使用 JMockit 进行单元测试的简单实现。实现如下


Team班级


public class Team {

    private TeamLeader teamLeader;

    public Team(TeamLeader teamleader) {

        this.teamLeader = teamleader;

    }


    public boolean hasDiscussion() {

        System.out.println("Discussion is hold by " + teamLeader.getName());

        Discussion discussion = new Discussion();

        return discussion.start();

    }

}

TeamLeader班级


public class TeamLeader {


    private String name;


    public TeamLeader(String name) {

        this.name = name;

    }


    public String getName() {

        return name;

    }

}

Discussion班级


public class Discussion {


    public boolean start() {

        return false;

    }

}

然后,我有一个单元测试来测试功能hasDiscussion如下


@RunWith(JMockit.class)

public class TeamTest {


    private Team team;


    @Test

    public void hasDiscussion(@Mocked TeamLeader teamLeader, @Mocked Discussion discussion) {


        new Expectations() {{

            teamLeader.getName(); result = "teamleader";

            discussion.start(); result = true;

        }};


        team = new Team(teamLeader);

        boolean actualResult = team.hasDiscussion();


        new Verifications() {{

            assertThat(actualResult, is(true));

        }};


    }

}

执行测试时,出现以下错误


Unexpected invocation of:

entity.Discussion#Discussion()

   on instance: entity.Discussion@7b70deb2

when was expecting an invocation of:

entity.Discussion#start()

   on mock instance: entity.Discussion@6f93ad02

mockit.internal.UnexpectedInvocation: Unexpected invocation of:

entity.Discussion#Discussion()

   on instance: entity.Discussion@7b70deb2

when was expecting an invocation of:

对这类问题有什么想法吗?


www说
浏览 87回答 1
1回答

收到一只叮咚

发生这种情况是因为您的hasDiscussion方法正在创建类的新实例Discussion,在这种情况下,您不能模拟它。要解决这个问题,您可以接收Discuss类作为方法的参数并发送模拟,我们在Team类构造函数中注入 Discuss 类。
随时随地看视频慕课网APP

相关分类

Java
我要回答