@Mock jpaRepository另一方面调用真正的保存方法@MockBean调用模拟方法

时间:2019-01-18 12:09:51

标签: java unit-testing spring-boot mockito junit4

我以为我了解@Mock@MockBean之间的区别,即使我以为被嘲笑的任何对象都不会调用真实方法,尽管我在测试下运行时可以看到hsqldb日志中已插入篮子。因此,现在我对为什么在使用@Mock时插入购物篮而不在使用@MockBean时插入购物篮感到困惑。

INSERT INTO BASKET VALUES(5,'ABCDEFGHIJ','ACTIVE',1,'2019-01-18 12:00:36.066000','2019-01-18 12:00:36.066000')

反之,如果我这样做,则hsqldb干净。在这两种情况下,测试都是成功的。

@MockBean
private BasketRepository basketRepo;

测试课程

@RunWith( SpringRunner.class )
@SpringBootTest( )
@ActiveProfiles( "test" )
public class BasketServiceTests
{

@SpyBean
private BasketService basketService;

@Mock
private BasketRepository basketRepo;

@Autowired
private UserAccountRepository userAccountRepo;

@Test
public void createBasketWithSameOrderRef() throws Exception
{
    UserAccount customer = userAccountRepo.findById( 1 )
            .orElseThrow( () -> new NotFoundException( "Customer not found" ) );

    Basket basket = new Basket();
    basket.setAudit( new Audit() );
    basket.setOrderRef( "ABCDEFGHIJ" );
    basket.setStatus( BasketStatusEnum.ACTIVE );
    basket.setUserAccount( customer );

    when( basketRepo.existsByOrderRef( anyString() ) ).thenReturn( false );
    when( basketRepo.save( isA( Basket.class ) ) ).thenReturn( basket );
    when( basketService.createOrderReference( ) ).thenReturn( "ABCDEFGHIJ" );

    Assert.notNull( basketService.getOrCreateByUserAccountBasket( customer ), "Basket id is null" );

}
}

服务

@Service
public class BasketService 
{
@Autowired
private BasketRepository basketRepo;

public Basket getOrCreateByUserAccountBasket( @NotNull final UserAccount userAccount )
{
    Optional<Basket> optBasket = basketRepo.findByUserAccountAndStatusActive( userAccount );

    if ( optBasket.isPresent() )
    {
        return optBasket.get();
    }

    String orderRef = null;

    do
    {
        orderRef = createOrderReference();
    }
    while( basketRepo.existsByOrderRef( orderRef ) );

    Basket basket = new Basket();
    basket.setAudit( new Audit() );
    basket.setOrderRef( orderRef );
    basket.setStatus( BasketStatusEnum.ACTIVE );
    basket.setUserAccount( userAccount );

    return basketRepo.save( basket );
}

public String createOrderReference()
{
    return RandomStringUtils.random( 10, true, false ).toUpperCase();
}
}

1 个答案:

答案 0 :(得分:3)

@MockBean是一种Spring注释,是集成测试中应该使用的注释,以便用模拟的注释替换实际的bean:

  

可用于向Spring添加模拟的注释   ApplicationContext。

Mockitos @Mock创建该存储库的模拟,但不将其注入BasketService

如果您确实需要使用Mockitos模拟版本,则必须在测试中手动进行:

@Mock
private BasketRepository basketRepo;

@Test
public void createBasketWithSameOrderRef() throws Exception
{
   basketService.setBasketRepository(basketRepo);
   ...