2018年8月2日 星期四

[Java] test Jersey injection

參考 StackOverflow:

// src/test/java/example/HellpResourceTest.java
package example;

import javax.inject.Inject;
import javax.ws.rs.core.Response;

import org.glassfish.hk2.api.ServiceLocator;
import org.glassfish.hk2.utilities.Binder;
import org.glassfish.hk2.utilities.ServiceLocatorUtilities;
import org.glassfish.hk2.utilities.binding.AbstractBinder;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Test;

import example.HelloResource;

class HelloResourceTest {
    @Inject
    private HelloResource resource;
    private ServiceLocator locator;

    @BeforeEach
    void setUp() {
        Binder resourceBinder = new AbstractBinder() {
            @Override
            public void configure() {
                // bind resource
                bindAsContract(HelloResource.class);
                // bind mock repository
                bind(new MockHelloRepository()).to(HelloRepository.class);
            }
        };
        locator = ServiceLocatorUtilities.bind(repositoryBinder, resourceBinder);
        locator.inject(this);
    }

    @AfterEach
    void tearDown() {
        if (locator != null) {
            locator.shutdown();
        }
    }

    @Test
    @DisplayName("Test Hello API")
    void doTest() {
        Assertions.assertNotNull(resource);
        Response response = resource.getHello("World");
        System.out.println(response);
        Assertions.assertEquals("Hello World", response);
    }

}

用到 org.glassfish.hk2:hk2-locator:2.5.0, org.glassfish.hk2:hk2-utils:2.5.0

參考資料:

沒有留言:

張貼留言

[Java] Invalid HTTP method: PATCH

最近系統需要使用 Netty4,所以把衝突的 Netty3 拆掉,然後就出現了例外。 pom.xml <dependency> <groupId>com.ning</groupId> <artifactId>as...