Java 单元测试

单元测试,常写常新。(指每次写都像新接触的一样。)

为什么不用 PowerMock

(什么字节码,什么不安全之类的。)

关于 Mockito

Mockito,读起来是不是很像一杯鸡尾酒 Mojito(音 /məˈhiːtəʊ/)?没错,他的 logo 就是这酒。

如何 mock 静态方法

将静态方法改写成动态工厂类

例:

如何 mock 方法内部的 new 操作

如果把 Mockito 换成 PowerMock 或者 Jmock 的话,这个 case 将是绝杀,但是换不得。

在 Test 里继承然后 Override 原方法

例:

1
2
3
4
5
6
7
8
9
10
public class Foo {
public int getInt() {
return getPrivateInt();
}

protected int getPrivateInt() {
// here "new Integer" represents anything that is a "new" operation
return new Integer(1);
}
}

对上面这个类,我们需要 mock 掉里面的 new 方法,这里就可以通过继承来实现:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
public class TestFoo {
@Test
public void testGetInt() {
TestableFoo foo = new TestableFoo();
assertEquals(1, foo.getInt());
}

private class TestableFoo extends Foo {
@Override
protected int getPrivateInt() {
return 1;
}
}
}
深得我心!博主晚餐加鸡腿!