2

I'm trying to create my first tests. I have to prove that a method returns a ContextLambda type, I am using the assertSame function to test it, but my test fails, I do not know what assert to use to test this, with assertEquals also fails. my test is something like that:

@Test
public void testCanCreateContextForLambda() {
    ContextFactory factory = new ContextFactory();

    LambdaContext context = factory.forLambda(
            new FakeRequest(),
            new FakeResponse(),
            new FakeLambda()
    );
    assertSame(LambdaContext.class, context);
}
kmilo93sd
  • 791
  • 1
  • 15
  • 35
  • 1
    You don’t need to assert. The fact that you could assign the value to a local variable of type LambdaContext is already a 100% guarantee that the type us what you expect. – Erwin Bolwidt Jul 01 '18 at 03:06
  • 1
    Java is a statically typed language. There is no point in testing the return type of a method (unless we are talking about polymorphism). – GhostCat Jul 01 '18 at 04:42

2 Answers2

4

Try using instanceof and assertTrue: Include assertTrue import:

import static org.junit.Assert.assertTrue;

And then the actual test:

@Test
public void testCanCreateContextForLambda() {
    ContextFactory factory = new ContextFactory();

    LambdaContext context = factory.forLambda(
            new FakeRequest(),
            new FakeResponse(),
            new FakeLambda()
    );
    assertTrue(context instanceof LambdaContext);
}

This assertion will be trivial and will always be true as long as context is a class of type LambdaContext (use interface for example to make it non-trivial).

dmitryro
  • 3,463
  • 2
  • 20
  • 28
  • There's another way of doing it using `assertThat`: https://stackoverflow.com/questions/12404650/assert-an-object-is-a-specific-type – dmitryro Jul 01 '18 at 02:49
  • The import for Junit5 is `org.junit.jupiter.api.Assertions.assertTrue`. – CoronA Jul 01 '18 at 04:28
  • i use assertThat( Object, instanceOf( AnotherObject) ); these dependencies belong to import static org.hamcrest.CoreMatchers.instanceOf; import static org.hamcrest.MatcherAssert.assertThat; – kmilo93sd Jul 01 '18 at 19:10
1

Your assertion with assertSame asserts that LambdaContext.class == context. This will never be true.

You could correct your assertion in several ways

  • context instanceof LambdaContext will be trivial (always true)
  • context.getClass() == LambdaContext.class will be almost trivial (probably always true)

These tests can be written using assertSame and assertTrue of the junit5 library (see other answers).

My best advice: Drop this test and write one that asserts non-trivial properties of context.

CoronA
  • 7,717
  • 2
  • 26
  • 53