I'm studying unit test, my first test project is lotto, so I wanna get six numbers using test.
I don't understand my error, where should I fix this code? getRandom is a method to get 1~45 number.
And getSixNumber is to get six numbers avoiding duplicated number using Set.
#Test
fun isSixNumber(){
var numbers = getSixNumber()
println(numbers)
assertEquals(6,numbers.size)
}
#Test
fun getSixNumber() : Set<Int> {
var lottoNum = setOf<Int>(6)
while(lottoNum.size!=6){
lottoNum.plus(getRandom())
}
return lottoNum
}
fun getRandom():Int{
return Random().nextInt(45)+1
}
ERROR
java.lang.Exception: Method getSixNumber() should be void
at org.junit.runners.model.FrameworkMethod.validatePublicVoid(FrameworkMethod.java:99)
at org.junit.runners.model.FrameworkMethod.validatePublicVoidNoArg(FrameworkMethod.java:74)
at org.junit.runners.ParentRunner.validatePublicVoidNoArgMethods(ParentRunner.java:155)
at org.junit.runners.BlockJUnit4ClassRunner.validateTestMethods(BlockJUnit4ClassRunner.java:208)
at org.junit.runners.BlockJUnit4ClassRunner.validateInstanceMethods(BlockJUnit4ClassRunner.java:188)
at org.junit.runners.BlockJUnit4ClassRunner.collectInitializationErrors(BlockJUnit4ClassRunner.java:128)
at org.junit.runners.ParentRunner.validate(ParentRunner.java:416)
at org.junit.runners.ParentRunner.<init>(ParentRunner.java:84)
at org.junit.runners.BlockJUnit4ClassRunner.<init>(BlockJUnit4ClassRunner.java:65)
at org.junit.internal.builders.JUnit4Builder.runnerForClass(JUnit4Builder.java:10)
at org.junit.runners.model.RunnerBuilder.safeRunnerForClass(RunnerBuilder.java:59)
at org.junit.internal.builders.AllDefaultPossibilitiesBuilder.runnerForClass(AllDefaultPossibilitiesBuilder.java:26)
at org.junit.runners.model.RunnerBuilder.safeRunnerForClass(RunnerBuilder.java:59)
at org.junit.internal.requests.ClassRequest.getRunner(ClassRequest.java:33)
at org.junit.internal.requests.FilterRequest.getRunner(FilterRequest.java:36)
at com.intellij.junit4.JUnit4IdeaTestRunner.startRunnerWithArgs(JUnit4IdeaTestRunner.java:49)
at com.intellij.rt.execution.junit.IdeaTestRunner$Repeater.startRunnerWithArgs(IdeaTestRunner.java:47)
at com.intellij.rt.execution.junit.JUnitStarter.prepareStreamsAndStart(JUnitStarter.java:242)
at com.intellij.rt.execution.junit.JUnitStarter.main(JUnitStarter.java:70)
As in Java, unit test methods aren't returning any value (void), mainly because it's a unit test and it results shouldn't be required/related to other tests,
Your fix is to remove return type:
#Test
fun getSixNumber() {
var lottoNum = setOf<Int>(6)
while(lottoNum.size!=6){
lottoNum.plus(getRandom())
}
return lottoNum
}
Related
I'm new in Unit Testing, I can't understand how to test this kind of method with kotlin, using MockK:
override fun register(firebaseId: String, uniqueId: String): Completable {
return Observable.just(0).observeOn(schedulerProvider.io()).flatMap {
val requestRegisterPushes = registerBuilder.build(firebaseId, uniqueId)
apiServiceFactory.build()
.registerPushes(requestRegisterPushes)
.subscribeOn(schedulerProvider.io())
.observeOn(schedulerProvider.ui())
}.flatMapCompletable {
Completable.complete()
}
}
This is my code for the test, the test was a success but the condition coverage does not increase.
#Test
fun `register_Test()`() {
val requestRegisterPushes = mockk<RequestRegisterPushes>(relaxed = true)
every { registerBuilder.build(any(), any(), any(), any()) } returns requestRegisterPushes
every { apiServiceFactory.build().register(requestRegisterPushes) } returns Observable.just(SimpleResponse())
val resp = userRepository.register("x7gbyb68837g78s", "XXX-XXX-XXX")
}
I would really appreciate it if you could help me a little.
Of course you don't have any coverage because code inside flatmap and flatMapCompletable operator was not executed.
You need to subscribe to Observable to make it emmit elements in you case it will emmit 0 only when you subscribe for it. That's how RxJava works. Something like this:
val subscriber = TestSubscriber<>();
val resp = userRepository.register("x7gbyb68837g78s", "XXX-XXX-XXX").subscribe(subscriber)
subscriber.assertComplete()
im new to unit testing. I am using junit5 for an aem 6.5 application. Im trying to write unit test so that i can migrate to cloud which has a requirement of atleast 50% unit test, thus what im doing now. My code has an init method for the getTags(). My unit test works fine but the jacoco reports a line that is not being covered. Any help would be appreciated to pint me in the right direction.
I have this class:
#Self
private SlingHttpServletRequest request;
#ValueMapValue
private List<String> tags;
#Override
public String getExportedType() {
return RESOURCE_TYPE;
}
#PostConstruct
public void init() {
Resource tagsNode = request.getResource().getChild("tags");
tags = new ArrayList<>();
if (tagsNode!=null) {
for (Resource child : tagsNode.getChildren()) {
TagModel tag = child.adaptTo(TagModel.class);
tags.add(tag.getTag());
}
}
}
public List<String> getTags() {
return this.tags;
}
And i have this unit test for aem
#Test
void testGetTags() {
List<String> expected = new ImmutableList.Builder<String>()
.add("4")
.add("22")
.build();
ctx.currentResource("/content/blog_placeholder");
BlogPlaceholderModel blogPlaceholderModel = ctx.request().adaptTo(BlogPlaceholderModel.class);
List<String> actual = blogPlaceholderModel.getTags();
assertEquals(expected, actual);
}
#Test
void testGetExportedType() {
final String expected = "furniture-row/components/content/blog-placeholder";
ctx.currentResource("/content/blog_placeholder");
BlogPlaceholderModel blogPlaceholderModel = ctx.request().adaptTo(BlogPlaceholderModel.class);
String actual = blogPlaceholderModel.getExportedType();
assertEquals(expected, actual);
}
For some reason my test is not covering the if condition:
what am i missing ? thanks
Your tests are covering this line partially.
You do have a test for the case that (tagsNode != null) == true but not for (tagsNode != null) == false. Therefore, the line is yellow to indicate that not all "branches" of the if statement are covered.
When I try to run my Junit tests (Wrote in Kotlin) I get the following exception :
java.lang.IllegalArgumentException: Attempted to find dependent attachment for class javax/xml/bind/DatatypeConverter, but could not find a suitable candidate.
I tried to comment/decomment some lines in following code, it seems that the exception occurs when I call command()
class IRIssueTests {
class DummyCommand : TypeOnlyCommandData()
private val ledgerServices = MockServices(listOf("com.my.package.name"))
private val ALICE = TestIdentity(CordaX500Name(organisation = "Alice", locality = "TestLand", country = "US"))
#Test
fun mustIncludeIssueCommand() {
val ir = IRState(
UniqueIdentifier(),
mutableListOf(ALICE.party)
)
ledgerServices.ledger {
transaction {
output(IRContract.ID, ir)
command(listOf(ALICE.publicKey), DummyCommand())
fails()
}
transaction {
output(IRContract.ID, ir)
command(listOf(ALICE.publicKey), IRContract.Commands.Issue())
verifies()
}
}
}
}
I would like to understand why I'm getting this exception and how to resolve it to make my test passing
Kotlin tests must be run with JDK8.
Change configuration of JDK8 in your project before running tests.
This will avoid this exception
With the logic of TDD in mind and trying to understand how to write unit test's, I am having trouble with Kotlin object. The test pass but I am unsure if this is actually the right test. I am trying to make sure that the Logger.i() method is called and that it saves into the database. But at the moment I am stuck at just its called part.
My Object
object Logger {
fun i(tag: String, msg: String, tr: Throwable? = null): Int {
insertIntoLogDatabase(createLogModel("i", tag, msg, tr))
return if (BuildConfig.DEBUG) Log.i(tag, msg, tr) else 0
}
private fun insertIntoLogDatabase(log: LogModel) {
//Insert into Log DB
logRepo.upsert(log)
}
private fun createLogModel(type: String, tag: String, msg: String, tr: Throwable?) = LogModel(0, type, tag, msg, if (tr != null) tr.message + "\n" + tr?.stackTrace.contentToString() else null)
fun setLogRepo(logRepo: LogRepository) {
this.logRepo = logRepo
}
}
with this, I know that I have to call Logger.setLogRepo(logRemp) to give the Logger access to the repo (and this works)
Where I am stuck is I am trying to unit test the Log.i method call
I have this
#Mock
lateinit var log: Logger
#Before
fun setUp() {
MockitoAnnotations.initMocks(this)
Logger.setLogRepository(logRepo)
}
#Test
fun `log i failed`() {
// When
log.i("Test", "Test1")
// Then
verify(log, times(1)).i("Test", "Test1")
}
I mean this works but is it correct (my gut tells me that something is wrong that I am not actually testing the Logger.i() method
please advise.
Thanks.
As you mentioned, you have to test that when you log the data, it should get stored in the repo in the format you want, and you want to test basically that when you have given the work of sending log to the Logger, it is getting sent to the repository in the correct format and you will assert against that.
So you're test case will look like,
#Mock
lateinit var logRepo: LogRepository
#Before
fun setUp() {
MockitoAnnotations.initMocks(this)
Logger.setLogRepository(logRepo)
}
#Test
fun `when an item is logged, it gets stored in the repository`()
{
val expectedData= <valueThatShouldBeSentToRepo>
Logger.i("Test", "Test1")
verify(logRepo).upsert(expectedData)
}
My problem is as follows:
I am trying to test multiple unit-tests in my controller in a Play Framework 2.4 application. I figured out I need to use a FakeApplication to run the FakeRequests to my controllers in, but for some odd reason the unit-tests work if I start and stop a new FakeApplication. If I start and stop the same FakeApplication, the first unit-test with a FakeRequest works, and the rest dont.
My question:
What am I doing wrong? Why are my unit-tests working if I start and stop a new FakeApplication, and why are they not working if I start and stop the same FakeApplication?
Here is my code snippet:
UnitTest class:
#Test
public void submitTestCorrectInput() {
final String input = CORRECT_INPUT;
final Result result = doCall(input);
assertThat(result.status(), is(equalTo(Http.Status.OK)));
}
#Test
public void submitTestIncorrectInput() {
final String input = INCORRECT_INPUT;
final Result result = doCall(input);
assertThat(result.status(), is(equalTo(Http.Status.NOT_FOUND)));
}
private Result doCall(final String input, final String max, final String filter) {
final Http.RequestBuilder requestBuilder = Helpers.fakeRequest(routes.Application.submit(input));
return route(requestBuilder);
}
Superclass from unittest class:
#Before
public void setUp() {
Play.start(Helpers.fakeApplication().getWrappedApplication());
}
#After
public void tearDown() {
Play.stop(Helpers.fakeApplication().getWrappedApplication());
}