gpt4 book ai didi

Java - 用于多个测试的模拟私有(private)静态构造函数

转载 作者:行者123 更新时间:2023-12-01 17:39:35 24 4
gpt4 key购买 nike

我是java测试的新手,现在已经摆弄了一会儿,但没有运气,我有以下类(class):

public class Bar {
public Object doSomething(int a, String b){
return "something";
}

public Object doSomethingElse(int a, int b, String c){
return "something else";
}
}
public class Foo {
private static Bar bar = new Bar();

public static void start(int a, int b, String c){
if(a == 1) { // some calculated condition
bar.doSomething(a, c);
} else {
bar.doSomethingElse(a, b, c);
}
}
}
@RunWith(PowerMockRunner.class)
@PrepareForTest(Foo.class)
public class FooTest {
@Test
public void somethingTest() throws Exception {
Bar barMock = createMock(Bar.class);

expectNew(Bar.class).andReturn(barMock);

expect(barMock.doSomething(1, "xxx")).andReturn("ABC");

replay(barMock, Bar.class);

Foo.start(1, 2, "xxx");
verify(barMock, Bar.class);
}

@Test
public void somethingElseTest() throws Exception {
Bar barMock = createMock(Bar.class);

expectNew(Bar.class).andReturn(barMock);

expect(barMock.doSomethingElse(0, 2,"xxx")).andReturn("ABC");

replay(barMock, Bar.class);

Foo.start(0, 2, "xxx");
verify(barMock, Bar.class);
}
}

单独运行测试可以,但不能运行整个类(class),我认为这与:

 private static Bar bar = new Bar();

但我不是 100% 确定。不管怎样,假设我无法更改 foo/bar 类,我该如何解决这个问题?

最佳答案

我会将 Foo 重构为:

public class Foo {
private static Bar bar = new Bar();

public static void start(int a, int b, String c){
if(a == 1) { // some calculated condition
doSomething(a, c);
} else {
doSomethingElse(a, b, c);
}
}

private static void doSomething(int a, String c) {
bar.doSomething(a, c);
}

private static void doSomethingElse(int a, int b, String c) {
bar.doSomethingElse(a, b, c);
}
}

并像这样测试 Foo:

import static org.mockito.Matchers.eq;

import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.AdditionalMatchers;
import org.powermock.api.mockito.PowerMockito;
import org.powermock.core.classloader.annotations.PrepareForTest;
import org.powermock.modules.junit4.PowerMockRunner;


@RunWith(PowerMockRunner.class)
@PrepareForTest({Foo.class})
public class FooTest {

@Before
public void setup() throws Exception {
PowerMockito.spy(Foo.class);
}


@Test
public void somethingTest() throws Exception {
Foo.start(1, 2, "xxx");
PowerMockito.verifyPrivate(Foo.class).invoke("doSomething", eq(1), eq("xxx"));
}

@Test
public void somethingElseTest() throws Exception {
Foo.start(0, 2, "xxx");
PowerMockito.verifyPrivate(Foo.class).invoke("doSomethingElse", AdditionalMatchers.not(eq(1)), eq(2), eq("xxx"));
}
}

并单独测试 Bar,这可以简单地使用 Mockito 完成。

关于Java - 用于多个测试的模拟私有(private)静态构造函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60981871/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com