繁体   English   中英

Mockito测试未调用verify()方法

[英]Mockito Test not invoking verify() method

我正在尝试使用Mockito和JUnit为应用程序设置单元测试。 该应用程序仅在SQL数据库上使用CRUD方法。 这些方法通过管理器层从DAO层链接到面向客户的服务层。 我要在此管理器层集中精力进行测试。

到目前为止,我仅对create方法进行了测试,它返回以下错误:

Wanted but not invoked:
dao.createEntry(profile);
-> at com.example.tests.ManagerCRUDTests.testProfileCreate(ManagerCRUDTests.java:60)
Actually, there were zero interactions with this mock.

我的代码如下:

public class ManagerCRUDTests {

    private final Logger logger = LoggerFactory.getLogger(ManagerCRUDTests.class.getName());

    @Mock
    private CrudDAO<Profiles> dao;

    @Mock
    private ProfileManagerImpl manager;

    @Mock
    Profile profile = new Profile();

    public Profile setProfile() {
        profile.setId(1);
        profile.setName("test");
        return profile;
    }

    @Before
    public void init() {
        MockitoAnnotations.initMocks(this);

    }

    @Test
    public void testProfileCreate() throws Exception {
        setProfile();
        logger.info("Testing create for Manager");
        logger.info("Parameters: {}", profile);
        manager.createEntry(profile);
        verify(dao).createEntry(ArgumentMatchers.eq(profile));  //this is where it is failing
        logger.info("Test passed");
    }

}

这是我第一次真正进行单元测试。 在此之前,我只做过集成测试。 在编写我的verify方法或模拟对象时,我做错了什么。

请更正您的经理以使其成为被测主题(而不是模拟对象),因此为了更正它,我建议:

如果使用注释,则无需在安装程序中执行initMocks

@Mock
private CrudDAO<Profiles> dao;

@InjectMocks
private ProfileManagerImpl managerUnderTest;

@Mock
Profile profile = new Profile();

public Profile setProfile() {
    profile.setId(1);
    profile.setName("test");
    return profile;
}

@Test
public void testProfileCreate() throws Exception {
    setProfile();
    logger.info("Testing create for Manager");
    logger.info("Parameters: {}", profile);
    managerUnderTest.createEntry(profile);
    verify(dao).createEntry(ArgumentMatchers.eq(profile));  
    logger.info("Test passed");
}

manager被定义为@Mock 因此它将不使用任何依赖项。 常见的做法是将manager@InjectMocks 这将创建一个实例,其中所有依赖项都被替换/设置为@Mock

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM