结合使用Dummy, InjectTo, PartialMock的单元测试

结合使用Dummy, InjectTo, PartialMock的单元测试, 备忘
@RunWith(UnitilsJUnit4TestClassRunner.class)
public class CheckerTest {
    private PartialMock<Manager> ManagerMock;
    private PartialMock<Dao1> daoMock;
    @TestedObject
    private Checker checker;
    @TestedObject
    private MyBean beanMock;
    @TestedObject
    private Result result;
    @TestedObject
    private MyBean2 bean2;
    // 在before方法之前执行(自定义)
    @CreateMock
    private MyBean bean3;

    @InjectIntoByType(target = "checker")
    @Dummy
    protected Dao1 dao1;

    @Before
    public void initMock() {
        bean3.setId(123L);
        bean3.setDescPath("abc");
    }
    private void setManager() throws IcException {
        result.setItem(bean2);
        ManagerMock.returns(result).queryById(null, null, null);
        checker.setManager(ManagerMock.getMock());
    }

    @Test
    public void testCheck() throws Exception {
        setManager();

        beanMock.setId(123L);

        daoMock.returns(bean3).query(0, 0, null);
        checker.setDao1(daoMock.getMock());
        checker.check(beanMock, "abc");
        assertEquals(beanMock.getMemo(), "abc");
    }

    @Test(expected = Exception.class)
    public void testCheck_和数据库中的id不等() throws Exception {
        setManager();

        beanMock.setId(111L);

        daoMock.returns(bean3).query(0, 0, null);
        checker.setDao1(daoMock.getMock());
        checker.check(beanMock, "abc");
    }

    @Test
    public void testCheck_没有指定id() throws Exception {
        setManager();

        daoMock.returns(bean3).query(0, 0, null);
        checker.setDao1(daoMock.getMock());
        checker.check(beanMock, "abc");
        assertEquals(beanMock.getMemo(), "abc");
        assertEquals(beanMock.getId(), 123L);
    }

    @Test(expected = Exception.class)
    public void testCheck_数据库中不存在() throws Exception {
        setManager();

        daoMock.returns(null).query(0, 0, null);
        checker.setDao1(daoMock.getMock());
        checker.check(beanMock, "abc");
    }
}

你可能感兴趣的:(单元测试)