3

Let's say I have a custom annotation

@ViewScope //<-- the issue
@Qualifier
@Component
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.TYPE, ElementType.FIELD,ElementType.PARAMETER,ElementType.METHOD, ElementType.ANNOTATION_TYPE})
public @interface Foo { ... }

I now want to test a method that is supposed to retrieve all the beans with that annotation.

How do I fake the vaadin session s.t. such an integration test

@RunWith(SpringJUnit4ClassRunner::class)
@SpringBootTest
@WebAppConfiguration
class FooAnnotationIT{

    @Autowired(required = false) //required=false --> empty list instead of exception when none are found
    @Foo
    val foos:List<Any> = mutableListOf()

    @Test
    fun `all beans are present`(){
        assertThat(foos.size).isEqualTo(5)
    }
}

succeeds instead of crashing with

org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'blah.blah.blah.FooAnnotationIT': Unsatisfied dependency expressed through field 'foos'
    Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'viewCache': Scope 'vaadin-ui' is not active for the current thread; consider defining a scoped proxy for this bean if you intend to refer to it from a singleton
    Caused by: java.lang.IllegalStateException: No VaadinSession bound to current thread
User1291
  • 7,664
  • 8
  • 51
  • 108

1 Answers1

4

Give Karibu Testing a shot https://github.com/mvysny/karibu-testing/tree/master/karibu-testing-v8

It has methods for mocking a Vaadin session, it supports V8 as well as V10+, and it even supports Kotlin!

Erik Lumme
  • 5,202
  • 13
  • 27
  • Played around with it a bit. Looks nice, haven't yet managed to integrate it into our app. (Think Spring Security is interfering somehow, not sure.) Will take a closer look when the timing is more appropriate. Thanks, though. – User1291 May 21 '19 at 08:39