0

In my test class, I insert a test product in setUp and delete it in tearDown. During mvn package, I get the following error:

java.lang.ClassCastException: java.lang.Integer cannot be cast to com.myproject.app.entity.Product
at com.myproject.app.MyProjectProductTests.tearDown

This is my service method to remove product by name, which uses JPA:

public Product remove(String productName) {
    return repository.removeByName(productName);
}

In my repository I define removeByName as follows:

@Transactional
Product removeByName(String name);

and this is the tearDown in my test class:

....
@Autowired
private ProductServiceImpl productService;
....

@After
public void tearDown() {
    this.productService.remove(productNameToTest);
}   

Why do I get that error for this tearDown?

6
  • so what does your removeByName() do? Commented Sep 10, 2019 at 21:28
  • It's a transactional method in repository. My aim is to remove the product by the given name. Commented Sep 10, 2019 at 21:29
  • Can you post the full stack trace? Commented Sep 10, 2019 at 21:44
  • removeByName method has either declared Integer as a return type, and/or has declared query or native query which returns int (e.g. it returns number of items deleted (int) instead of the deleted Product item). Just guessing. Commented Sep 10, 2019 at 21:47
  • does your removeByName() work at all? I mean, outside unit tests? it doesn't sound like this problem relates to teardown at all, but faulty service method Commented Sep 10, 2019 at 22:01

2 Answers 2

2

This:

@Transactional
Product removeByName(String name);

to me looks like a faulty signature. You can choose return value between an integer (return count of deleted entries) or list of VO:s (return all deleted objects). However, one object is not an acceptable return value. This should work:

@Transactional
long removeByName(String name);

and

@Transactional
List<Product> removeByName(String name);

and even

@Transactional
void removeByName(String name);

but not the thing you have.

Sign up to request clarification or add additional context in comments.

1 Comment

This is the answer thank you. I'm new to java but I should have known about type casting.
0

Try updating query Product removeByName(String name); to Product deleteByName(String name);

1 Comment

Same error. May be I shouldn't try to add a transactional method but write a custom repository method to delete instead.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.