kmilo93sd
kmilo93sd

Reputation: 901

Test method return specific object junit

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);
}

Upvotes: 2

Views: 6092

Answers (2)

dmitryro
dmitryro

Reputation: 3516

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).

Upvotes: 4

CoronA
CoronA

Reputation: 8095

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.

Upvotes: 1

Related Questions