![](/img/trans.png)
[英]How to mock the dtabase in J2EE for junit without spring boot
[英]How to access static variable initialised with @Mock in spring boot in Junit
我有以下組件 class。
@Component
class ComponentClass{
private static AnotherClass anotherClass;
@Autowired
private void setAnotherClass(AnotherClass a){
anotherClass = a;
}
public AnotherClass getAnotherClass(){
return anotherClass;
}
}
@RunWith(MockitoJUnitRunner.class)
public class ComponentClassTest {
@InjectMocks
private ComponentClass componentClass;
@Mock
private AnotherClass anotherClass;
@Test
public void testGetAnotherClass() {
Assert.assertNotNull(ComponentClass.getAnotherClass());
}
}
當我嘗試運行測試用例時,getAnotherClass 方法返回 null。 任何人都可以在這里幫助為什么 getAnotherClass 方法調用沒有返回模擬實例。
擴展@m-deinum:該示例有一個帶有非靜態設置器的static字段。 由於許多原因,這是不好的做法(包括 Mockito 不會觸摸它)。 Spring 默認情況下會確保 AnotherClass 是 singleton 所以我建議通過構造函數參數設置它。 Spring 和 Mockito 都會對此感到滿意。
private final AnotherClass anotherClass;
public ComponentClass(AnotherClass anotherClass) {
this.anotherClass = anotherClass;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.