1. 程式人生 > >spring-boot整合Mock進行單元測試

spring-boot整合Mock進行單元測試

1.引包

<dependency>

            <groupId>org.springframework.boot</groupId>

            <artifactId>spring-boot-starter-test</artifactId>

            <scope>test</scope>

</dependency>

<dependency>

            <groupId>junit</groupId>

<artifactId>

junit</artifactId>

            <scope>test</scope>

</dependency>

2.上程式碼  

BeanTest.java

@RunWith(SpringJUnit4ClassRunner.class)  

@SpringApplicationConfiguration(classes = TestApplication.class) //使用TestApplication作為spring容器載入類

@ActiveProfiles("test")   //這邊test指配置檔案指向spring-test.yml

@Rollback(false) //單元測試配置資料庫預設會事務會退  此時強制事務提交

public class BeanTest {

@Mock

protected IdentityFactory factory;

@InjectMocks

@Autowired

private IdGenerator idGenerator;

@Before

public void mockIdentityFactory() {

    Mockito.when(factory.next(Mockito.anyString())).thenAnswer(new Answer<Long>() {

         @Override

         public Long answer(InvocationOnMock invocationOnMock) throws Throwable {

              Random random = new Random();

              return (long) random.nextInt(1000);

         }

   });

}

@Test

public void test(){

     idGenerator.getId();

}

}

@SpringBootApplication

public class TestApplication {

      public static void main(String[] args) {

           SpringApplication.run(TestApplication.class, args);

      }

}

上面這個例子IdGenerator就注入了IdentityFactory的例項,當執行到方法到actory.next會產生一個隨機值

注意:

Mock在執行時匹配注入的一個條件是class匹配(class相同或者是其子類)  

當Mock的類是一個介面;在spring ioc載入bean 對於介面預設產生動態代理的方式,此時會導致條件匹配失敗;此時更改預設使用cglib方式載入bean即可.