Home Mock objects in spring async methods
Reply: 0

Mock objects in spring async methods

Renan
1#
Renan Published in 2017-12-06 21:27:52Z

I'm trying test a method with async annonation, that call a repository to save in dabatase the process of computation from this method, and i try mock this repository but when i execute the async method get real repository not mock repository, how to get mock object in async method?:

Note: If remove the @Async the method get mock repository

My method:

@Async
public void method() {
    // some computation
    this.repository.save();
}

My test:

@RunWith(SpringRunner.class)
@SpringBootTest
@ActiveProfiles("test")
public class AServiceTests {

    @Mock
    private Repository repository;

    @Autowired
    @InjectMocks
    private OneService oneService;

    @Before
    public void setUp() {
        MockitoAnnotations.initMocks(this);
        when(repository.save(any(Y.class))).thenReturn(null);
    }

    @Test
    public void test_method(){
        oneService.method();
    }
}

My Service:

@Service
public class OneService {

    private final Repository repository;

    @Autowired
    public OneService(Repository repository) {
        this.repository = repository;
    }

    @Async
    public void method() {
        // some computation
        this.repository.save();
    }
}
You need to login account before you can post.

About| Privacy statement| Terms of Service| Advertising| Contact us| Help| Sitemap|
Processed in 0.297774 second(s) , Gzip On .

© 2016 Powered by mzan.com design MATCHINFO