有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

导航属性的java模拟加载

这是我的代码的一个非常简化的版本,它说明了具体的问题

有什么方法可以控制accountProductRepository运行时发生的事情吗。是否从测试中调用refresh()

不知何故,我需要在buyProduct()方法中创建的AccountProductPojo上设置ProductPojo,以便在访问getProduct()时不会得到空指针。getName()属性

刷新使用javax。坚持不懈实体管理器。refresh()根据buyProduct()方法中设置的id加载导航属性

public class ProductServiceTest {
    @InjectMocks
    IProductService productService = new ProductService();
    @Mock
    IWriteANoteService writeANoteService;
    @Mock
    IAccountProductRepository accountProductRepository;

    @Test
    public void buyProductTest() {
        productService.buyProduct(1l, 1l);
    }
}

@Service
public class ProductService implements IProductService {
    @Autowired
    IWriteANoteService writeANoteService;

    @Autowired
    IAccountProductRepository accountProductRepository:

    public void buyProduct(Long productId, Long accountId) {
        AccountProductPojo accountProduct = new AccountProductPojo();
        accountProduct.setProductId(productId);
        accountProduct.setAccountId(accountId);

        accountProductRepository.persist(accountProduct);
        // load navigation properties
        accountProductRepository.refresh(accountProduct);

        writeANoteService.writeAccountNote(accountId, "Bought product " + accountProduct.getProduct().getName());
    }
}

@Entity
@Table(name = "account_product")
public class AccountProductPojo {
    @Id
    @Column(name = "id")
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;

    @Column(name = "account_id")
    private Long accountId;

    @Column(name = "product_id")
    private Integer productId;

    @ManyToOne
    @JoinColumn(name = "product_id", insertable = false, updatable = false)
    private ProductPojo product;

    @OneToOne(fetch = FetchType.LAZY, targetEntity = AccountPojo.class)
    @JoinColumn(name = "account_id", insertable = false, updatable = false)
    private AccountPojo account;

    // getters and setters
}

共 (1) 个答案

  1. # 1 楼答案

    这似乎是mocking a void method的一个相当典型的例子

    你可以试试这样:

        Mockito.doAnswer(new Answer() {
              public Object answer(InvocationOnMock invocation) {
                  Object[] args = invocation.getArguments();
                  AccountProductPojo accountProduct = (AccountProductPojo) args[0];
                  accountProduct.setProduct(new ProductPojo(PRODUCT_ID_CONSTANT, PRODUCT_NAME_CONSTANT));
                  return null;
              }}).when(accountProductRepository).refresh(Mockito.any());
    

    这里的关键是,在模拟上调用refresh()时,可以在POJO上调用setProduct(),POJO作为参数传递给refresh()调用,以避免以后出现空指针异常