Mokito在运行JUnit测试时不与Jersey和Jetty合作



当测试Jersey REST OrderResource时,它返回空List<Order> orders。Mockito部分似乎工作不正确,因为它正在访问数据库层。如何解决?

测试

 public class OrderResourceTest extends JerseyTest {
    @Mock
    private OrderService orderServiceMock;
    @Override
    protected Application configure() {
        MockitoAnnotations.initMocks(this);
        enable(TestProperties.LOG_TRAFFIC);
        enable(TestProperties.DUMP_ENTITY);
        //database set up
        ResourceConfig resourceConfig = new ResourceConfig(OrderResource.class);
        return resourceConfig;
    }
    @Test
    public void testGetOrders() {
        when(orderServiceMock.findOrders()).thenReturn(getMockOrders());
        Response response = target("/orders")
            .request()
            .get();
        List < Order > orders = response.readEntity(new GenericType < List < Order >> () {});
        assertEquals("Should return status 200", 200, response.getStatus());
        assertTrue(orders.size() == 1); // orders.size() is 0. Why?
    }

    private List < Order > getMockOrders() {
        Customer customer = new Customer(1 L, "CompanyName", "Street", "123456", "City", "UK");
        List < OrderLine > orderLines = Arrays.asList(new OrderLine(1 L, "s345664lkdLDSDf", "Samsung Galaxy 4", 1));
        Order order = new Order(1 L, customer, orderLines);
        return Arrays.asList(order);
    }
}

该项目被用作参考

示例中缺少的关键部分是InjectableProvider

class InjectableProvider extends AbstractBinder implements Factory<CustomerService> {
    @Override
    protected void configure() {
        bindFactory(this).to(CustomerService.class).in(Singleton.class);
    }
    public CustomerService provide() {
        return serviceMock;
    }
    public void dispose(CustomerService service) {
        serviceMock = null;
    }
}

提供者的工作是将模拟注入资源。如果您遵循相同的方法并针对您的OrderService自定义它,则应调用您的模拟。

请确保在配置期间注册它:

config.register(new InjectableProvider());

相关内容

  • 没有找到相关文章

最新更新