I got the following method:
private MessageDigest getMessageDigest() {
try {
return MessageDigest.getInstance("MD5");
} catch (NoSuchAlgorithmException e) {
throw new Error(e);
}
}
To get 100% code coverage I need to get into the catch block. But I am absolutely not sure how I can do that. Is there some mocking framework that could help me in this case? If so - how? Or is there even another way without having to catch an exception?
The getInstance method on MessageDigest looks like a static method. Static methods cannot be mocked. I agree with ratchet that you should not aim for 100 % code coverage but focus on testing the areas with complex code instead.
I'd write this as:
try {
return MessageDigest.getInstance("MD5");
} catch (NoSuchAlgorithmException e) {
throw (AssertionError)new AssertionError("unreachable").initCause(e);
}
And declare that because the catch block is unreachable, it doesn't need to be tested.
honestly in this case you don't need to cover that code it's non reachable boilerplate to ensure you don't have to worry about checked exceptions in the user code (most of the time 98% coverage is sufficient if you can explain why the 2 percent got missed)
Just to have a follow-up on this question, it can be done with PowerMock.
As an extract, this is my working code:
#RunWith(PowerMockRunner.class)
#PrepareForTest({MyClass.class, MessageDigest.class})
public class MyClassTest {
private MyClass myClass = new MyClass();
#Mock private MessageDigest messageDigestMock;
#Test
public void shouldDoMethodCall() throws Exception {
setupMessageDigest();
String value = myClass.myMethodCall();
// I use FestAssert here, you can use any framework you like, but you get
// the general idea
Assertions.assertThat(value).isEqualToIgnoringCase("hashed_value");
}
public void setupMessageDigest() throws Exception {
PowerMockito.mockStatic(MessageDigest.class);
when(MessageDigest.getInstance("SHA1")).thenReturn(messageDigestMock);
when(messageDigestMock.digest(Matchers.<byte[]>anyObject())).thenReturn("hashed_value".getBytes());
}
}
The class "MyClass" will simply do something like:
public class MyClass {
public String myMethodCall() {
return new String(MessageDigest.getInstance("SHA1").digest("someString".getBytes()));
}
}
In an additional test, you could write
when(MessageDigest.getInstance("SHA1")).thenThrow(new NoSuchAlgorithmException());
instead of my mentioned return, to get to your catch block.
Do note, however, that using PowerMock has some drawbacks. It will generally use more memory and more instatiation time, so your test will run longer. For this specific test, it won't make a big difference, but just as a head's up.
Your exception is unreachable because that exception will never be thrown. I suppose it's logical with something like Mockito to do something akin to:
doThrow(new NoSuchAlgorithmException()).when(MessageDigest.getInstance("MD5")); // this is psuedo code
But it still doesn't make much sense. You are better off writing your code like:
private static final MessageDigest MD5_DIGEST;
static {
try {
MD5_DIGEST = MessageDigest.getInstance("MD5");
///CLOVER:OFF
} catch (Exception e) {
// can't happen since MD5 is a known digest
}
///CLOVER:ON
}
public MessageDigest getMessageDigest() {
return MD5_DIGEST;
}
otherwise you'll need to modify your method to be testable:
public MessageDigest getMessageDigest(String digest) throws NoSuchAlgorithmException {
return MessageDigest.getInstance(digest);
}
In my case, our pipeline needs 100% coverage, so I did the following:
define a static inner class with only one static method to return the instance of MessageDigest
define the method just as #TomAnderson did: in catch clause, throw an AssertionError("unreachable", e) to indicate that it is definitely impossible to reach here
ignore this static class in jacoco.gradle for jacocoTestReport and jacocoTestCoverageVerification tasks. To know how to exclude inner class, check my other post: How to ignore inner static classes in Jacoco when using Gradle
(which links to another post of how to do it in Maven, in case you use it)
I extract the method to a class, because Gradle does not have a consistent syntax to ignore members in a class. Check Filtering options of Jacoco and here
You can create a wrapper MessageDigest class:
#Component
public class MessageDigest {
public java.security.MessageDigest getInstance(String algorithm) throws NoSuchAlgorithmException {
return java.security.MessageDigest.getInstance(algorithm);
}
}
Related
I am writting test for a try catch block, but I am quite confused about how to test the catch block...especially it uses slf4j to log the error.
addText here is the another method from the same class.
public class TextQueue {
public void addTextToQueue(final Text text) {
try {
if (text != null) {
addText(text);
}
} catch (final JsonProcessingException e) {
LOGGER.error("Error adding text to the queue : {}", e);
}
}
}
here is my test case
#RunWith(MockitoJUnitRunner.class)
public class TextQueueTest {
private org.slf4j.Logger LOGGER = LoggerFactory.getLogger(TextQueueTest.class);
private static final String MY_TEXT = "src/text.json";
private Text text;
private final ObjectMapper mapper = new JacksonConfig().dateAsStringObjectMapper();
#Mock
private TextQueue textQueue;
#Before
public void setUp() throws IOException {
text = mapper.readValue(new File(TextQueueTest.MY_TEXT), Text.class);
}
#Test
public void addTextToQueue() {
try{
textQueue = spy(textQueue);
textQueue.addTextToQueue(text);
}catch(final Exception e){
LOOGER.error("add text to queue threw an error" + e);
}
}
can anyone help me solve this problem?
First of all, you should really read a good tutorial about Mockito, like the one from vogella. You see, you are simply throwing together a lot of things that are non-sensical.
Like:
#Mock
private TextQueue textQueue;
to then have
textQueue = spy(textQueue);
within your test case. You should be really clear about this. A spy is build on a real instance of your class under test. Creating a spy that spies on a mock, as said: that makes no sense.
Then:
}catch(final Exception e){
Logger.error("add text to queue threw an error" + e);
Again, non-sensical. The whole idea of your unit tests is that they fail when something is wrong. When your production code throws unexpected exceptions, you don't log them, you just let them fail your test case in the end.
To answer the actual question: it looks like your production code is using a specific "constant" logger instance. Given that design, the only way to check your production code would be to:
make that LOGGER a mocked object
somehow inject it into an instance underTest of your production code class
trigger that method to test on underTest (and somehow force the method to throw an exception)
verify that the mocked LOGGER saw the expected call to error()
We can't give better advise, because your code input isn't sufficient, we don't really know what your production class is doing (for example: we don't know what LOGGER is, and where it is coming from. if it happens to be a static variable, then most likely, you can't get "control" over it with Mockito).
In any case, you probably actually need the spy concept. In order to test addTextToQueue() you need a way to invoke the "real" addTextToQueue() implementation, but the call to addTser() within needs to go to a mock (so that you can control what that call does).
But as said: start by really researching how Mockito works, instead of throwing together things that make no sense in some "trial and error" approach. Correct unit testing with mocking is complicated, you can't learn that by "trial and error".
I have such problem, as topikstarter here - Using PowerMockito.whenNew() is not getting mocked and original method is called
But I have java 1.4, junit 3.8.1 and jmock 1.2 - and no annotations, of course.
Problem is as it seems in this link - I have a method, which makes new Example(), and then calls Example.someMethod(); I need to get exception from this method to test it. In more wide terms, I need to know how to PowerMockito(or use any other framework) objects in java 1.4 - with junit 3 and without annotations. Make fake object, make any method take this mock object in "new", not create one, and mock it's methods. There is no even method PowerMockito.whenNew() in PowerMockito for junit3...
Any docs, "getting started"s and other things would help - I haven't found anything about PowerMockito for junit3, except of maven dependency link.
public class Example(){
ExampleHelper helper = new ExampleHelper(5);
public void doSmth(){
try{
int i = returnPlus();
System.Out.Println("Nope, we shouldn't come here. We need to visit Catch block");
} catch (myException e){
System.Out.Println("Hoooray, exception!");
}
}
//different package
public class ExampleHelper{
int i;
public ExampleHelper(int i){
this.i = i;
}
public int returnPlus() throws myException{//Yes, method signature tells us, that we are THROWING ecxeption
return i+1;//yes, method DO NOT throws exception
}
}
I'm trying to do something like this, but it doesn't work. In PowerMockito for junit3 there is no such methods - and if I trying to do this with PowerMock+Mockito - there should be annotations, and I have java 4 with no annotations aboard...
public class TestHarderExample extends TestCase {
public void testSomething() {
ExampleHelper exampleHelper = PowerMockito.mock(com.sources.ExampleHelper.class);
Example example = new Example();
try {
PowerMockito.whenNew(ExampleHelper.class).withAnyArguments().thenReturn(exampleHelper);
PowerMockito.when(exampleHelper.giveAplus()).thenThrow(new IOException("Dummy one"));
Example.doSmth();
} catch (IOException e) {
System.out.println("Good one!");
} catch (Exception e){
System.out.println("Bad one...");
}
So, I had to create two files. One is a class definition. The other one uses the class' methods/fields.
(Artifact.java) Artifact Class definition:
public class Artifact {
int artNumber;
String arcName;
String artType;
int artYear;
double artWeight;
Artifact(int artNumber, String arcName, String artType, int artYear,double artWeight) {
this.artNumber = artNumber;
this.arcName = arcName;
this.artType = artType;
this.artYear = artYear;
this.artWeight = artWeight;
}
public void changeArtYear(int x) {
this.artYear = x;
}
public void changeArcName(String x) {
this.arcName = x;
}
public int getArtNumber() {
return artNumber;
}
public String getArcName() {
return arcName;
}
public String getArtType() {
return artType;
}
public int getArtYear() {
return artYear;
}
public double getArtWeight() {
return artWeight;
}
public String toString(){
return("The artifact #"+artNumber+" was discovered by "+arcName+". The artifact is made of "+artType+" and was discovered in "+artYear+". The artifact weighs "+artWeight+" kilograms.");
}
}
(ArtifactTester.java) Testing methods:
public class ArtifactTester {
public static void main(String[] args){
Artifact test = new Artifact(88888888,"ben","clay",1624,46.4);
System.out.println(test.toString()); //toString()
System.out.println(test.getArtWeight()); //getArtWeight()
System.out.println(test.getArtYear()); //getArtYear()
System.out.println(test.getArtType()); //getArtType()
System.out.println(test.getArcName()); //getArcName()
System.out.println(test.getArtNumber()); //getArtNumber()
test.changeArcName("zack");
test.changeArtYear(1400);
System.out.println(test.getArcName()); //getArcName()
System.out.println(test.getArtYear()); //getArtYear()
}
}
Anyways, my teacher to told me to add exception handling, but I am not sure where I would add exception handling.
Question: Is it possible to use exception handling in this situation?
Well to be blunt. Yes. Of course. You can use exception handling wherever and whenever you please (most of the time). Although, in this specific case I don't really see a good reason for it. But, I'll take your word for the need.
Now, as for where to handle exceptions, this is up to you. You can add exception handling in one of two places. You can either add exception handling when you call the methods like this:
try { //try executing a block of code which may throw exception
test.toString()
}
catch(Exception e) { //use Exception for all types of exceptions, or make it specific
//do something here if the exception is thrown
}
or you can excpetion handle in the methods themselves like so:
public void changeArtYear(int x) {
try{
this.artYear = x;
}
catch(Exception e){ //catch the exception that could be thrown
//do something
}
}
This should do the trick in your case if you want to add exception handling here. However, I would strongly urge you to learn exception handling and the different exceptions in Java, it is one of the most improtant fundamentals to programming in this language.
Also, let me point this out again: In this program, there is really no need to use exception handling except for practice. There is nothing here that would throw an exception for any reason. (Except maybe a NullPointerException if you passed a null parameter through one of your method calls)
Good Reference/Tutorial:
http://www.tutorialspoint.com/java/java_exceptions.htm
This site is an excellent java reference point in general, but specifically for your question today, this page shows you how to work with exceptions.
Is it possible to use exception handling in this situation?
I don't think so. You should probably go and ask your teacher.
In your code, Artifact is just a POJO (Plain Old Java Object). It would not throw any exceptions. All you do in the class is getters and setters, right? How can that throw any exceptions?
You can throw exceptions though. In your setters, you can check whether the argument is null before setting it to the fields. For example:
public void changeArcName(String x) {
if (x == null) throw new ArgumentException ("x is null!");
this.arcName = x;
}
Alternatively, you can just use brute force and use try...catch. like this:
Artifact test = new Artifact(88888888,"ben","clay",1624,46.4);
try {
System.out.println(test.toString()); //toString()
System.out.println(test.getArtWeight()); //getArtWeight()
System.out.println(test.getArtYear()); //getArtYear()
System.out.println(test.getArtType()); //getArtType()
System.out.println(test.getArcName()); //getArcName()
System.out.println(test.getArtNumber()); //getArtNumber()
test.changeArcName("zack");
test.changeArtYear(1400);
System.out.println(test.getArcName()); //getArcName()
System.out.println(test.getArtYear()); //getArtYear()
} catch (Exception ex) {
ex.printStackTrace ();
}
Warning: The catch block can never be reached!
I don't know whether the above is what your teacher wants. Just try both methods and hand it in and see what he/she says!
Something I've always been curious of
public class FileDataValidator {
private String[] lineData;
public FileDataValidator(String[] lineData){
this.lineData = lineData;
removeLeadingAndTrailingQuotes();
try
{
validateName();
validateAge();
validateTown();
}
catch(InvalidFormatException e)
{
e.printStackTrace();
}
}
//validation methods below all throwing InvalidFormatException
Is is not advisable to include the try/catch block within my Constructor?
I know I could have the Constructor throw the Exception back to the caller. What do you guys prefer in calling methods like I have done in Constructor? In the calling class would you prefer creating an instance of FileDataValidator and calling the methods there on that instance? Just interested to hear some feedback!
In the code you show, the validation problems don't communicate back to the code that is creating this object instance. That's probably not a GOOD THING.
Variation 1:
If you catch the exception inside the method/constructor, be sure to pass something back to the caller. You could put a field isValid that gets set to true if all works. That would look like this:
private boolean isValid = false;
public FileDataValidator(String[] lineData){
this.lineData = lineData;
removeLeadingAndTrailingQuotes();
try
{
validateName();
validateAge();
validateTown();
isValid = true;
}
catch(InvalidFormatException e)
{
isValid = false;
}
}
public boolean isValid() {
return isValid;
}
Variation 2:
Or you could let the exception or some other exception propagate to the caller. I have shown it as a non-checked exception but do whatever works according to your exception handling religion:
public FileDataValidator(String[] lineData){
this.lineData = lineData;
removeLeadingAndTrailingQuotes();
try
{
validateName();
validateAge();
validateTown();
}
catch(InvalidFormatException e)
{
throw new com.myco.myapp.errors.InvalidDataException(e.getMessage());
}
}
Variation 3:
The third method I want to mention has code like this. In the calling code you have to call the constructor and then call the build() function which will either work or not.
String[] lineData = readLineData();
FileDataValidator onePerson = new FileDataValidator();
try {
onePerson.build(lineData);
} catch (InvalidDataException e) {
// What to do it its bad?
}
Here is the class code:
public FileDataValidator() {
// maybe you need some code in here, maybe not
}
public void build(String[] lineData){
this.lineData = lineData;
removeLeadingAndTrailingQuotes();
try
{
validateName();
validateAge();
validateTown();
}
catch(InvalidFormatException e)
{
throw new com.myco.myapp.errors.InvalidDataException(e.getMessage());
}
}
Of course, the build() function could use a isValid() method that you call to see if its right but an exception seems the right way to me for the build function.
Variation 4:
The fourth method I want to mention is what I like best. It has code like this. In the calling code you have to call the constructor and then call the build() function which will either work or not.
This sort of follows the way JaxB and JaxRS work, which is a similar situation to what you have.
An external source of data - you have a file, they have an incoming message in XML or JSON format.
Code to build the objects - you have your code, they have their libraries of code working according the specifications in the various JSRs.
Validation is not tied to the building of the objects.
The calling code:
String[] lineData = readLineData();
Person onePerson = new Person();
FileDataUtilities util = new FileDataUtilities();
try {
util.build(onePerson, lineData);
util.validate(onePerson);
} catch (InvalidDataException e) {
// What to do it its bad?
}
Here is the class code where the data lives:
public class Person {
private Name name;
private Age age;
private Town town;
... lots more stuff here ...
}
And the utility code to build and validate:
public FileDataValidator() {
// maybe you need some code in here, maybe not
}
public void build(Person person, String[] lineData){
this.lineData = lineData;
removeLeadingAndTrailingQuotes();
setNameFromData(person);
setAgeFromData(person);
setTownFromData(person);
}
public boolean validate(Person person) {
try
{
validateName(person);
validateAge(person);
validateTown(person);
return true;
}
catch(InvalidFormatException e)
{
throw new com.myco.myapp.errors.InvalidDataException(e.getMessage());
}
}
You should consider the static factory pattern. Make your all-arguments constructor private. Provide a static FileDataValidator(args...) method. This accepts and validates all the arguments. If everything is fine, it can call the private constructor and return the newly created object. If anything fails, throw an Exception to inform the caller that it provided bad values.
I must also mention that this:
catch (Exception e) {
printSomeThing(e);
}
Is the deadliest antipattern you could do with Exceptions. Yes, you can read some error values on the command line, and then? The caller (who provided the bad values) doesn't get informed of the bad values, the program execution will continue.
My preference is for exceptions to be dealt with by the bit of code that knows how to deal with them. In this case I would assume that the bit of code creating a FileDataValidator knows what should happen if the file data is not valid, and the exceptions should be dealt with there (I am advocating propagating to the caller).
Whilst discussing best practice - the class name FileDataValidator smells to me. If the object you're creating stores file data then I would call it FileData - perhaps with a validate method? If you only want to validate your file data then a static method would suffice.
I've read this: Can I use throws in constructor? -- which gave me the right idea, and led me to one answer, but was not very explicit. I've also read several others, but could not find my answer. To recap what I've learned for context, essentially, this will not compile...
public ExampleClass(String FileName)
{
this(new FileInputStream(FileName));
}
public ExampleClass(FileInputStream FileStream)
{
DoSomethingToSetupBasedUponFileStream(FileStream);
}
...because the FileInputStream constructor (called from the String Constructor) may throw a FileNotFoundException. You can still create the constructor by making it throw the same exception as follows:
public ExampleClass(String FileName) throws FileNotFoundException
{
this(new FileInputStream(FileName));
}
My question is related to a default constructor (no arguments) that would simply use a default filename String constant:
public ExampleClass() throws FileNotFoundException
{
this(DEFAULT_FILE_NAME);
}
This would chain the constructors as:
ExampleClass() --> ExampleClass(<String>) --> ExampleClass(<InputFileStream>)
In a case like this, is it possible to use a default value (static final class member) in the default constructor, to instantiate (further down the chain) a FileInputStream, but not have to use the throws FileNotFoundException code (which would require someone using the class to either re-throw or handle the exception?
If I could do something like the following, I would handle the exception myself:
public ExampleClass()
{
try
{
this(DEFAULT_FILE_NAME);
}
catch (Exception e)
{
DoSomethingToHandleException(e);
}
}
...However, as far as I know this is not possible, because the "Constructor call must be the first statement in a constructor"
Being more used to .Net at this point, I've never been forced to deal with exceptions if I didn't really want to... :D
Refactor your file construction code out of your constructor, so you could do something like this --
public ExampleClass() {
try {
fileInputStreamMethod(DEFAULT_FILE);
}
catch(Exception e) {
...
}
public ExampleClass(String fileName) throws Exception {
fileInputStreamMethod(fileName);
}
private void fileInputStreamMethod(String fileName) throws Exception {
// your file handling methods
}
You are correct that you cannot catch an exception from the call to this(...).
You could use a static method to produce what you want:
static ExampleClass createDefault()
{
try
{
return new ExampleClass(DEFAULT_FILE_NAME);
}
catch(Exception e)
{
DoSomethingToHandleException(e)
}
}
You could do something like this:
public ExampleClass(String FileName)
{
this(getStream(FileName));
}
private static FileInputStream getStream(String name) {
try {
return new FileInputStream(name);
} catch (Exception e) {
// log error
return null;
}
}
The real question is, why would you not want to throw an exception? How should your program behave if the file cannot be opened? I think it would be unusual that you would want it to proceed as if there were no problem. Quite likely, the null input stream will cause grief later on.
In general, you're better off throwing an exception as close to the source of an error as possible.
Basically what you have to do is do the work that your constructor has to do in a different method(something that's not a constructor) and then use it in the default constructor. But am not sure how useful this technique is in your scenario.
cheers!