只需使用您的常規Spring配置。在測試類中,聲明要用@Capturing
模擬的類型。它會嘲笑Spring使用的任何實現類。
編輯:在下面添加完整的示例代碼。
import javax.inject.*;
public final class MyApplication {
private final String name;
@Inject private SomeService someService;
public MyApplication(String name) { this.name = name; }
public String doSomething() {
String something = someService.doSomething();
return name + ' ' + something;
}
}
public final class SomeService {
public String getName() { return null; }
public String doSomething() { throw new RuntimeException(); }
}
import org.springframework.context.annotation.*;
@Configuration
public class MyRealApplicationConfig {
@Bean
SomeService getSomeService() { return new SomeService(); }
@Bean
MyApplication getMyApplication(SomeService someService) {
String someName = someService.getName();
return new MyApplication(someName);
}
}
import javax.inject.*;
import org.junit.*;
import org.junit.runner.*;
import static org.junit.Assert.*;
import mockit.*;
import org.springframework.test.context.*;
import org.springframework.test.context.junit4.*;
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = MyRealApplicationConfig.class)
public final class MyApplicationSpringTest {
@Inject MyApplication myApplication;
@Mocked SomeService mockService;
@BeforeClass // runs before Spring configuration
public static void setUpMocksForSpringConfiguration() {
new MockUp<SomeService>() {
@Mock String getName() { return "one"; }
};
}
@Test
public void doSomethingUsingMockedService() {
new Expectations() {{ mockService.doSomething(); result = "two"; }};
String result = myApplication.doSomething();
assertEquals("one two", result);
}
}
import org.junit.*;
import static org.junit.Assert.*;
import mockit.*;
// A simpler version of the test; no Spring.
public final class MyApplicationTest {
@Tested MyApplication myApplication;
@Injectable String name = "one";
@Injectable SomeService mockService;
@Test
public void doSomethingUsingMockedService() {
new Expectations() {{ mockService.doSomething(); result = "two"; }};
String result = myApplication.doSomething();
assertEquals("one two", result);
}
}
謝謝 - 將調查此方法。 – FrVaBe
不幸的是,如果在Spring上下文初始化期間需要模擬實例,則這不起作用。問題是:如何在測試之外生成一個具有已定義行爲的jmockit模擬實例? – FrVaBe
模擬API僅用於* inside *測試。但是我不清楚實際問題是什麼。在上下文初始化期間Spring *調用bean的方法嗎? –