簡體   English   中英

如何在為 controller 創建單元測試用例時在服務中注入屬性值

[英]How to inject properties values in service while creating the unit test case for controller

我正在開發一個 micronaut 應用程序,我在服務 class 中添加了一個屬性注入,如下所示:

@Value("${scheduler.jobtime}")
private final String cronExpr;

這是我的服務 class 的樣子:

@Context
@AllArgsConstructor
@Slf4j
public class MyService {
    private final ExternalApiClient externalApiClient;
    private final OtherService1 otherService1;
    

    @Value("${scheduler.jobtime}”)
    private final String cronExpr;

    public Job createJob() {
        
       // Method definition using externalApiClient
    }

    public boolean haveStartedToday() {
        return otherService1.somemethod(cronExpr);
    }
}

當我添加此屬性時,我的以下測試用例失敗了

@MicronautTest(transactional = false)
@Tag("integration")
class ControllerTest {
    private static final UUID ID = UUID.randomUUID();
    @Inject
    @Client("/")
    HttpClient client;

    @Inject
    MyService myService;

    @MockBean(MyService.class)
    @Context
    MyService myService() {
        final MyService mock = mock(MyService.class);
        when(mock.createJob()).thenReturn(Job.builder()
                .status(“CREATED”)
                .fullLoad(true)
                .build());
        return mock;
    }

    @Test
    void executeJob() throws JSONException {
        HttpResponse<String> response = client.toBlocking()
            .exchange(HttpRequest.POST(“/job”, ""), String.class);

        verify(myService).createJob();

        assertThat(response.code()).isEqualTo(HttpStatus.OK.getCode());
        Map<String, Object> hashMap = Map.of("id", ID, "status", “CREATED”);
        JSONAssert.assertEquals(response.body(), new JSONObject(hashMap), 
        JSONCompareMode.LENIENT);
    }
}

我可以看到錯誤如下

Bean definition [com.endpoints.job.$ControllerTest$MyService0Definition$Intercepted] could not be loaded: Error instantiating bean of type  [com.endpoints.job.$ControllerTest$MyService0Definition$Intercepted]

我相信這是因為在服務 class 中添加了屬性,但不確定如何解決這個問題。

任何人都可以建議我是否遺漏任何東西。

謝謝

沒有復制器無法復制您的確切問題。

可能的問題是因為龍目島。

@Context
@AllArgsConstructor // Creates MyService(String str) constructor
public class MyService {

    // Without @AllArgsConstructor this won't compile because it is final
    @Value("${my.property}")
    private final String str; 

    public String doSomething() {
        return "doSomething -> property: " + str;
    }
}

使用 Micronaut 版本 3.8.3,我得到的錯誤是:

io.micronaut.context.exceptions.BeanInstantiationException: Bean definition [com.example.MyService] could not be loaded: Failed to inject value for parameter [str] of class: com.example.MyService

Message: No bean of type [java.lang.String] exists. Make sure the bean is not disabled by bean requirements (enable trace logging for 'io.micronaut.context.condition' to check) and if the bean is enabled then ensure the class is declared a bean and annotation processing is enabled (for Java and Kotlin the 'micronaut-inject-java' dependency should be configured as an annotation processor).
Path Taken: new MyService(String str) --> new MyService([String str])

因為 Micronaut 不知道你想在構造函數中使用什么“String”。

更新

如果將@AllArgConstructor更改為@RequiredArgsConstructor則有效。

@Context
@RequiredArgsConstructor
public class MyService {

    private final Transformer transformer; //Injected by constructor

//    @Value("${my.property}") //Works, but use @Property 
    @Property(name = "my.property") //Preferred over @Value
    protected String str; //Cannot be final! Private requires reflection. 

    public String doSomething() {
        return transformer.transform(str);
    }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM