문제

I have an abstract class, AbstractService, and several classes which extend this abstract class:

Silly class diagram

I then have a ServiceFactory that returns me a generic list with some services, according to a parameter I pass:

public class ServiceFactory {
    public List<? extends AbstractService> getServices(final MyParameter param) {
        // Service is an interface implemented by AbstractService
        List<Service> services = new ArrayList<>();

        for (Foo foo : param.getFoos()) {
            services.add(new AService(foo.getBar()));
        }
        // creates the rest of the services
        return services;
    }
}

In my UnitTest, I'd like to verify if my list of services contains exactly 3 AService subtypes. The way I'm doing that now is:

@Test
public void serviceFactoryShouldReturnAServiceForEachFoo() {
  // I'm mocking MyParameter and Foo here
  Mockito.when(param.getFoos()).thenReturn(Arrays.asList(foo, foo, foo);

  AService aservice = new AService(foo);

  List<AService> expectedServices = Arrays.asList(aservice, aservice, aservice);
  List<? extends AbstractService> actualServices = serviceFactory.getServices();

  assertTrue(CollectionUtils.isSubCollection(expectedServices, actualServices));
}

When actualServices contains less than 3 Aservice, the test fails correctly. The only problem with this solution is that if actualServices contains more than 3 AService, the test passes...

Is there a method that does that or should I implement it myself using loops?

도움이 되었습니까?

해결책

You could use hamcrest Matchers.

hamcrest-library contains matchers to check collection/iterable contents.

I hope the following sample matches your szenario loosely

import static org.hamcrest.CoreMatchers.not;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.mockito.Mockito.mock;
import static org.hamcrest.Matchers.containsInAnyOrder;

import java.util.ArrayList;
import java.util.Collection;

import org.apache.commons.lang.builder.EqualsBuilder;

import org.junit.Test;

public class ServiceFactoryTest
{
    @Test
    public void serviceFactoryShouldReturnAServiceForEachFoo()
    {
        Foo foo = mock( Foo.class );
        Service service = new AService( foo );
        Service[] expected = { service, service, service };
        Service[] tooFew = { service, service };
        Service[] tooMany = { service, service, service, service };

        ServiceFactory factory = new ServiceFactory();

        assertThat( factory.createServices( foo, foo, foo ), containsInAnyOrder( expected ) );
        assertThat( factory.createServices( foo, foo, foo ), not( containsInAnyOrder( tooFew ) ) );
        assertThat( factory.createServices( foo, foo, foo ), not( containsInAnyOrder( tooMany ) ) );
    }

    interface Foo
    {}

    interface Service
    {}

    class AService implements Service
    {
        Foo foo;

        public AService( Foo foo )
        {
            this.foo = foo;
        }

        @Override
        public boolean equals( Object that )
        {
            return EqualsBuilder.reflectionEquals( this, that );
        }
    }

    class ServiceFactory
    {
        Collection<? extends Service> createServices( Foo... foos )
        {
            Collection<Service> list = new ArrayList<>();

            for ( Foo foo : foos )
            {
                list.add( new AService( foo ) );
            }

            return list;
        }
    }
}

다른 팁

It is definitely the case that subtypes of AService are instances of AService and the condition returning true is correct.

There isn't even a good way to implement it using loops and a lot depends on the execution context, "same" classes loaded from different class loaders are "different".

I would take a step back and think about the property of AService that you wish to verify, should that property be defined in AbstractService? And, finally use the property to verify the results.

A big thanks to Max Fichtelmann to point me in the right direction!

I ultimately started using Fest assert, but the same result can probably be achieved with Hamcrest.

I created a custom matcher, assertEvery, comparing list sizes:

public class ServiceAssert extends AbstractAssert<ServiceAssert, List<Service>> {
  public ServiceAssert(List<Service> actual) {
    super(actual, ServiceAssert.class);
  }

  // it's usually assertThat, but it conflicts with the List<T> assertions
  public static ServiceAssert assertThatMy(List<Service> actual) {
    return new ServiceAssert(actual);
  }

  public ServiceAssert containsEvery(List<? extends Service> expectedServices) {
    Integer listSize = 0;

    isNotNull();

    if (expectedServices == null || expectedServices.isEmpty()) {
      throw new AssertionError("Do not use this method for an empty or null list of services, use doesNotContain instead.");
    }

    Class<? extends Service> serviceClass = expectedServices.get(0).getClass();

    for (Service f : actual) {
      if (f.getClass().equals(serviceClass)) {
        listSize++;
      }
    }

    if (listSize != expectedServices.size()) {
      throw new AssertionError("expected " + expectedServices.size() + " " + serviceClass.getSimpleName() + " but was " + listSize + ".");
    }

    return this;
  }
}

Now, I can use it with import static myassertions.impl.ServiceAssert.assertThatMy;.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top