簡體   English   中英

在一種測試方法上使用 Mockito 使其他測試方法失敗

[英]Using Mockito on one test method making other Test methods fail

我正在為我正在測試的服務 class 創建集成測試,我需要為其中一種測試方法模擬 dao。 問題是當我一起運行測試時,我的一些測試失敗了,但是當我單獨運行它們時,測試過去了。 如果我刪除 mockito 部分,當我一次運行它們時,我的所有測試都會通過。 對此的任何見解表示贊賞

下面是我的代碼:

 // here is my Service class
 public class Service {

 Dao dao;

 public Dao getDao() {
    return dao;
}

public void setDao(Dao dao) {
    this.dao = dao;
}
}

//here is my integ test

@Category(IntegrationTest.class)
@RunWith(SpringRunner.class)
public class Test{

@Rule
public ExpectedException thrown = ExpectedException.none();

@Autowired
@Qualifier(Service.SERVICE_NAME)
protected Service service;

@Before
public void setUp() {
    assertNotNull(service);
}

@Test
public void testDoSomethingOne() throws Exception {
    Dao dao = Mockito(Dao.class)
    service.setDao(dao)
    boolean flag = service.doSomething();
    Assert.assertTrue(flag);
}

@Test
public void testDoSomethingTwo() throws Exception {

    Integer num = service.doSomething();
    Assert.assertNotNull(num);
}

測試方法testDoSomethingOne()為它為測試的 rest 保留的服務實例設置模擬 dao。

使用 @DirtiesContext 注釋方法testDoSomethingOne testDoSomethingOne()以獲取與后續測試方法關聯的新上下文。

測試注釋,指示與測試關聯的 ApplicationContext 是臟的,因此應該關閉並從上下文緩存中刪除。

如果測試修改了上下文,則使用此注釋 - 例如,通過修改 singleton bean 的 state,修改 state bean,修改 state 將提供相同上下文的新上下文的測試,等等。

您可以在每次測試之前獲取 dao 並在測試后將其分配回服務,如下所示:

private static Dao dao;

@Before
public void setUp() {
    if(dao == null) {
       dao = service.getDao();
    }
}

@After
public void tearDown() {
     service.setDao(dao);
}

如果是集成測試,您不應該模擬您的 daos,推薦的方法是使用 memory 數據庫中的 a ,例如H2 spring 人員已經提供了注釋@DataJpaTest ,它可以為您創建數據庫。

You can use the @DataJpaTest annotation to test JPA applications. By default, it scans for @Entity classes and configures Spring Data JPA repositories. If an embedded database is available on the classpath, it configures one as well. Regular @Component beans are not loaded into the ApplicationContext.

https://docs.spring.io/spring-boot/docs/current/reference/htmlsingle/#boot-features-testing-spring-boot-applications-testing-autoconfigured-jpa-test

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM